我有来自字符串键的字典,我想使用 Linq 获取相应键的值
Why do you want to get a value from a Dictionary using LINQ? You can just get the value using:
int value = dictionary[key];
You could use Single
, but it's totally pointless and more code:
var keyValuePair = dictionary.Single(x => x.Key == key);
int value = keyValuePair.Value;
Why use Linq for something that is built in?
var val = myDict[key];
Use Linq where it makes sense (querying collections), not for something that is already well handled by the Dictionary
classes.
returns the string value in this particular instance.
Disctionary<int, string> CustomValues = new Dictionary<int, string>();
CustomValues[int]; //CustomValues[key];
To Get the Value from the Dictionary 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.
Output: Mithra
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.