简体   繁体   English

使用字典列表中的特定键获取所有不同的值<string, string>

[英]Get all different values with a certain key in list of dictionary<string, string>

I have a list of Dictionaries. 我有一个字典清单。

List<Dictionary<String, String>> data = GetData();

The dictionaries contain a key named "Month" with values like "1/2010" etc. I need a list of strings with all different months that appear in the Dictionary-list. 字典包含一个名为“ Month”的键,其值类似“ 1/2010”等。我需要一个包含所有不同月份的字符串列表,这些字符串出现在字典列表中。

Simple with LINQ: 使用LINQ很简单:

var months = data.Select(dict => dict["Month"]).Distinct().ToList();

Or if not all of the dictionaries had the entry: 或者,如果不是所有的词典都有条目:

var months = data.Select(dict => {
                            string value;
                            bool hasValue = dict.TryGetValue("Month", out value);
                            return new { value, hasValue };
                         })
                 .Where(p => p.hasValue)
                 .Select(p => p.value)
                 .Distinct()
                 .ToList();

EDIT: My original version didn't include the Distinct call, so it would have included duplicates. 编辑:我的原始版本不包含Distinct调用,因此它将包含重复项。 It now won't. 现在不会了。

Or if you want a one-liner (yields distinct values, and still works if not all dictionaries have the entry) 或者,如果您想要单线(产生不同的值,并且即使不是所有的词典都有条目,它仍然可以工作)

var result=data.SelectMany(x => x)
   .ToLookup(kv => kv.Key, kv => kv.Value)["Month"].Distinct().ToList();

If you can't use LINQ: 如果您不能使用LINQ:

List<string> months = new List<string>();
foreach (Dictionary<string, string> aDict in data)
{
    string aMonth;
    if (aDict.TryGetValue("Month", out aMonth))
        months.Add(aMonth);
}

EDIT: 编辑:

If you don't want duplicates: 如果您不想重复:

List<string> months = new List<string>();
foreach (Dictionary<string, string> aDict in data)
{
    string aMonth;
    if (aDict.TryGetValue("Month", out aMonth) && !months.Contains(aMonth))
        months.Add(aMonth);
}

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

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