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
CodePudding user response:
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);
CodePudding user response:
var result =
list.Select(dict => dict.ContainsKey( "Language" ) ? dict[ "Language" ] : null )
.Where( val => val != null );
CodePudding user response:
Use SelectMany
to flatten the lists:
var result = obj.SelectMany(c => c
.Where(dict => dict.Key == "Language"))
.Select(dict => dict.Value);
However, it will iterate through the list for you - there is no other way.