简体   繁体   English

从列表中获取唯一值 <Dictionary<string, string> &gt;

[英]Get Unique values from List<Dictionary<string, string>>

I have List<Dictionary<string, string>> object with some datas in it. 我有List<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 */

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". 我想在字典中获取不同的值( List<string> ),其中键等于“ccc”,键“bbb”的值等于“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>> . 返回一个字符串列表,其中包含字符值,其中key等于“ccc”,并且键“bbb”的值等于List<Dictionary<string, string>>中的“bbbValue1”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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