开发者

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 i开发者_如何学编程n the Dictionary-list.


Simple with 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. 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:

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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜