[英]Get Value from key using linq
我有來自字符串鍵的字典,我想使用 Linq 獲取相應鍵的值
為什么要使用 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.
輸出:密特拉
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.