简体   繁体   中英

Get Unique values from List<Dictionary<string, string>>

I have List<Dictionary<string, string>> object with some datas in it.

/* 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 */

I want to get the distinct values( List<string> ) in the dictionary where the key is equal to "ccc" and the value of the key "bbb" is equal to "bbbValue1".

Expected Result:

Return a string list contains the dictionary value where key is equal to "ccc" and the value of the key "bbb" is equal to "bbbValue1" in the List<Dictionary<string, string>> .

I think you want:

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

or if you want the result as a set:

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

EDIT : You've changed your question completely, which isn't a nice thing to do (ask a new one instead), but to answer it in its current state:

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

Think it will be better to flatten list like this:

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

I think this will give you the correct result:

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();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM