If I have an enumeration of dictionaries
IEnumerable<IDictionary<string, float>> enumeration
can I perform a Linq query on it so that I can select by a value from each dictionary in the enumeration using the same key?
I can do this in a loop:
float f;
foreach (var dictionary in enumeration)
{
if (dictionary.TryGetValue("some key", out f))
{
Console.WriteLine(f);
}
}
(The eventual plan is to compare the performance of the query verses the equivalent nested looping statements (the enumeration itself is formed from either another query or an equivalent set of loops).)
Are you looking for something like this:
This query first identifies which dictionaries in the sequence contain the specified key, and then for each of those retrieves the value for the given key.
This is not as efficient as a loop which uses
TryGetValue(), because it will perform two dictionary accesses – one for theWhereand another for theSelect. Alternatively, you could create a safe method that returns a value or a default from the dictionary, and then filter out the defaults. This eliminates the duplicate dictionary lookup.