我有一个字符串类型的字典,想要使用 Linq 获取对应键的值。
int value = dictionary[key];
你可以使用Single
,但这完全没有意义,反而增加了代码量:
var keyValuePair = dictionary.Single(x => x.Key == key);
int value = keyValuePair.Value;
为什么要使用 Linq,它不是内置的吗?
var val = myDict[key];
在有意义的情况下(查询集合),使用 Linq,而不是已经能够很好处理的 Dictionary
类。
返回此特定实例中的字符串值。
Disctionary<int, string> CustomValues = new Dictionary<int, string>();
CustomValues[int]; //CustomValues[key];
获取字典键的值
Dictionary<int,string>dict=new Dictionary<int,string>();
dict.Add(1,"Maha");
dict.Add(2,"Malathi");
dict.Add(3,"Mithra");
dict.Add(4,"Saravana");
var val=dict.Where(x=>x.Key==key).Select(x=>x.Value);//get the value from dictionary where key=3
(or)
var val=dict[Key];//get the value for Dictionary key 3.
输出:Mithra
var value = myDictionary["myKey"];
呢? - Øyvind Bråthen