var dic = new Dictionary<KeyValuePair<int, int>, string>(); dic.Add(new KeyValuePair<int,int>(0, 1), "墙里秋千墙外道,墙外行人,墙里佳人笑"); dic.Add(new KeyValuePair<int,int>(0, 2), "入我相思门,知我相思苦,长相思兮长相忆,短相思兮无穷极"); dic.Add(new KeyValuePair<int,int>(1, 1), "有美人兮,见之不忘;一日不见兮,思之如狂"); dic.Add(new KeyValuePair<int,int>(1, 2), "直道相思了无益,未妨惆怅是清狂");
如代码段所示的集合,如何用Lambda表达式获取Value,我的想法是传入两个int获取对应Value,比如传入0,1返回"墙里秋千墙外道,墙外行人,墙里佳人笑",传入1,1返回"有美人兮,见之不忘;一日不见兮,思之如狂"... ...万望高手指点
string value = dic.Where(m => m.Key.Key == 1 && m.Key.Value == 1).FirstOrDefault().Value;
FirstOrDefault后记得判断是否为null再取值
代码如下:
public class Program
{
public static void Main(string[] args)
{
var dic = new Dictionary<KeyValuePair<int, int>, string>();
dic.Add(new KeyValuePair<int, int>(0, 1), "墙里秋千墙外道,墙外行人,墙里佳人笑");
dic.Add(new KeyValuePair<int, int>(0, 2), "入我相思门,知我相思苦,长相思兮长相忆,短相思兮无穷极");
dic.Add(new KeyValuePair<int, int>(1, 1), "有美人兮,见之不忘;一日不见兮,思之如狂");
dic.Add(new KeyValuePair<int, int>(1, 2), "直道相思了无益,未妨惆怅是清狂");
//(0,1)
var value01 = dic.Where(x => x.Key.Key == 0 && x.Key.Value == 1).FirstOrDefault().Value;
Console.WriteLine(value01);
//(1,1)
var value11 = dic.Where(x => x.Key.Key == 1 && x.Key.Value == 1).FirstOrDefault().Value;
Console.WriteLine(value11);
}
}