Get All Values, by Key, In a List of Dictionaries

Viewed 72

I have a list of Dictionaries, like so: IEnumerable<IDictionary<string, object?>>

I would like to get all values (object) from said list of dictionary, where Key = "Language"

How can I do this using LinQ, without iterating through all of my list?

Thank you a lot in advance

3 Answers

You can avoid a double lookup using TryGetValue

var result = list
    .Select(dict => dict.TryGetValue("Language", out var lang) ? lang : null)
    .Where(val => val != null);

Use SelectMany to flatten the lists:

var result = obj.SelectMany(c => c
                      .Where(dict => dict.Key == "Language"))
                      .Select(dict => dict.Value);

Do note @Charlieface answer is better because it makes use of the dictionaries optimized lookup functionality - avoiding one loop.

var result = 
   list.Select(dict => dict.ContainsKey( "Language" ) ? dict[ "Language" ] : null )
       .Where( val => val != null );
Related