2012-09-18 249 views
2

我有List<Dictionary<string, string>>對象,其中包含一些數據。從列表中獲取唯一值<Dictionary <string,string >>

/* Values in the list will be like 
    [0] - 
     aaa - aaaValue1 (Key, Value) 
     bbb - bbbValue1 
     ccc - cccValue1 
     ddd - dddValue1 
    [1] - 
     aaa - aaaValue2 (Key, Value) 
     bbb - bbbValue2 
     ccc - cccValue2 
     ddd - dddValue2 

    and so on */ 

我想在字典中,以獲得不同的值(List<string>),其中的關鍵是等於「CCC」,並將鍵「BBB」的值等於「bbbValue1」。

預期結果:

返回一個字符串列表包含字典中值,其中關鍵是等於「CCC」,並將鍵「BBB」的值等於「bbbValue1」在List<Dictionary<string, string>>

回答

8

我想你想:

var result = testData.Where(dict => dict.ContainsKey("EmpNo")) 
        .Select(dict => dict["EmpNo"]) 
        .Distinct() 
        .ToList(); 

,或者如果你想要的結果爲一組:

var result = new HashSet<string>(from dict in testData  
           where dict.ContainsKey("EmpNo")   
           select dict["EmpNo"]);   

編輯: 你已經完全改變了你的問題,這是不一個好的事情要做(而不是要求一個新的),但要回答它在當前的狀態:

var result = testData.Where(dict => dict.ContainsKey("ccc") 
           && dict.ContainsKey("bbb") 
           && dict["bbb"] == "bbbValue1") 
        .Select(dict => dict["ccc"]) 
        .Distinct() 
        .ToList() 
0

認爲這將是更好的拉平名單如下:

testData.SelectMany(x => x) 
     .Where(x => x.Key == "EmpNo") 
     .Select(x => x.Value) 
     .Distinct() 
     .ToList(); 
+0

這將返回IEnumberable 的'序列'不'名單' ..所以你應該在'.Distinct()' –

+0

之後添加'.ToList()'。我的回答後問題發生了變化。 – Dima

+0

@Dima對不起。我只問了一個新問題。但由於倒票,我不得不刪除它,所以我修改了這個問題。 –

0

我覺得這會給你正確的結果:

var result = testData.SelectMany(dict => dict) 
        .Where(dict => dict.Key.Equals("ccc") || (d.Key.Equals("bbb") && d.Value.Equals("bbbValue1"))) 
        .Select(d => d.Value).Distinct().ToList(); 
相關問題