2013-03-27 49 views
-9

我收集了字典。Linq在字典集合

public class Bills 
    { 
     public Dictionary<string, string> billList { get; set; } 
    } 

從這節課「比爾」 List<Bills> allBills的實例的列表,我將如何得到所有情況鍵等於「用戶」和名稱等於記錄「尼克」

+0

請給出您當前的方法並告訴我們它的問題究竟是什麼。 – 2013-03-27 10:49:47

+0

你試過了什麼? – 2013-03-27 10:49:55

回答

4

其他的答案中沒有充分利用詞典的查找速度:

var matches = allBills 
     .Where(dict => dict.billList.ContainsKey("User")) 
     .Where(dict => dict.billList["User"] == "Nick"); 
+0

比我好,+1 :) – mattytommo 2013-03-27 10:57:21

+1

爲什麼不在'.Where(dict => {string name; return dict.billList.TryGetValue(「User」,out name)&& name ==「Nick」;});' 只做一次字典查找然後 – 2013-03-27 10:58:06

+0

是的 - 可以做到這一點 - 很確定幕後的「trygetvalue」,它做的是完全相同的事情 - 我認爲這更具可讀性。 – 2013-03-27 11:02:51

1
string key = "User"; 
string name = "Bill"; 

if (billList.ContainsKey(key)) 
{ 
    string result = billList[key]; 
    if (result == name) 
     return result; 
} 
return null; // key and names did not match 

詞典將永遠不會有超過一個 occurence相同的密鑰的,所以我不知道,如果你不應該使用Dictionary<string, Bill>代替,在這種情況下,代碼會看起來更象這樣:

return billList.Where(kvPair => kvPair.Value.Key == key && 
           kvPair.Value.Name == name).Select(kvPair => kvPair.Value); 

此代碼假定Bill類包含一個Key和一個Name字段。