Choosing a value from multiple dictionaries inside an enumeration

If I have a list of dictionaries

IEnumerable<IDictionary<string, float>> enumeration

Is it possible to execute a Linq query on it so that I can select by 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);
    }
}

(A possible plan is to compare query performance with equivalent nested loop operators (the enumeration itself is formed either from another query or from an equivalent set of loops).

+3
source share
4 answers

You are looking for something like this:

IEnumerable<float> vals = enumeration.Where( d => d.ContainsKey( "some key" ) )
                                     .Select( d => d["some key"] );

This query first determines which dictionaries in the sequence contain the specified key, and then for each of them retrieves the value for the given key.

, , TryGetValue(), - Where, Select. , , , . .

public static class DictionaryExt {
    public static TValue FindOrDefault<TKey,TValue>( 
            this Dictionary<TKey,TValue> dic,
            TKey key, TValue defaultValue )  
    {
        TValue val;
        return dic.TryGetValue( key, out val ) ? val : defaultValue;
    }
}

enumeration.Select( d => d.FindOrDefault( "some key", float.NaN ) )
           .Where ( f => f != float.NaN );
+5

LINQ over objects .NET, , , - - LINQ , - - , , .

- :

var q = from d in enumeration
        where d.ContainsKey("some key")
        select d["some key"];

foreach (float f in q)
{
    Console.WriteLine(f);
}
+2

TryGetValue:

float f = 0.0f;
foreach (var dic in enumeration.Where(d => d.TryGetValue("some key", out f))) {
  Console.WriteLine(f);
}
+1

... Lookup.

 //run once
ILookup<string, float> myLookup = enumeration
  .SelectMany(d => d)
  .ToLookup(kvp => kvp.Key, kvp => kvp.Value);

 //run many times
foreach(float f in myLookup["somekey"])
{
  Console.WriteLine(f);
}

, , IEnumerable<float> ( ).

+1
source

Source: https://habr.com/ru/post/1748428/


All Articles