Katia S.
Katia S.

Reputation: 287

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

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

Upvotes: 2

Views: 628

Answers (3)

Stefan
Stefan

Reputation: 17698

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.

Upvotes: 1

Charlieface
Charlieface

Reputation: 72511

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

Upvotes: 3

Terry
Terry

Reputation: 1998

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

Upvotes: 0

Related Questions