Linq. Help fake code

Please help minimize the following code: There is a class with a dictionary property:

class Foo
{
    public int Field { get; set; }
    public Dictionary<int, bool> dic { get; set; }
}

And a list of instances of foo. I want to get a federated dictionary from all instances of a class:

...

var items = new List<Foo>
    {
        new Foo {Field = 1, Dic = new Dictionary<int, bool> {{1, true}, {2, false}}},
        new Foo {Field = 2, Dic = new Dictionary<int, bool> {{3, true}, {2, false}}}
    };
    var result = new Dictionary<int, bool>();

    foreach (var dics in items.Select(x => x.Dic))
        foreach (var pair in dics)
            if (!result.ContainsKey(pair.Key))
                result.Add(pair.Key, pair.Value);

    // testing output 
    foreach (var pair in result)
        Console.WriteLine("{0}, {1}", pair.Key, pair.Value);

Is it possible to do this with a clean LINQ approach? Thanks in advance!

+3
source share
3 answers

You can use SelectManyto capture and smooth the internal elements of the dictionary:

var result = items.SelectMany(f => f.Dic)
                  .GroupBy(pair => pair.Key)
                  .ToDictionary(g => g.Key, g => g.First().Value);

edit: , , DistinctBy Jon Skeet morelinq. , GroupBy , , , - . , First, :

var result = items.SelectMany(f => f.Dic)
                  .DistinctBy(pair => pair.Key)
                  .ToDictionary(pair => pair.Key, pair => pair.Value);
+6
var result =
    (from item in items
     from pair in item.Dic
     group pair by pair.Key
     ).ToDictionary(g => g.Key, g => g.First().Value);
+2

I don't know if it is better Distinct, but it is shorter for the record.

var result = items.SelectMany(d => d.Dic)
                  .Distinct()
                  .ToDictionary(p => p.Key, p => p.Value);

But I really like to use foreachfor this.

var result = new Dictionary<int, bool>();

foreach (var dic in items.SelectMany(d => d.Dic))
    result[dic.Key] = dic.Value;
+1
source

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


All Articles