user1027620
user1027620

Reputation: 2785

How to get distinct values from nested lists of objects?

I have the following problem:

foo f = new foo();
// ...
f.bars.SelectMany(m => m.qux.GroupBy(x => x.hash))
      .Select(group => group.First())
      .Sum(s => s.size);

This returns the sum of the total size property for qux within a single bar instance. Adding another qux object with an existing hash value in another bar is ignored so its size value is counted in the computed sum. (Even tho the same qux exists in another bar object).

How can I tweak my query to make sure all objects having the same hash are calculated once?

The data structure would look like this:

class foo
{
    public List<bar> bars = new List<bar>();
}

class bar
{
    public List<qux> qux = new List<qux>();
}

class qux
{
    public string hash { get; set; }
    public int size { get; set; }
}

Upvotes: 0

Views: 1136

Answers (1)

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34631

Judging from your data structure, here is what you need:

int sizeSum =
    bars.SelectMany(m => m.qux)
        .GroupBy(q => q.hash)
        .Select(g => g.First())
        .Sum(q => q.size);

The difference with your initial solution is that we first get a unified list with .SelectMany(), and only then do we group it by hash.

Upvotes: 2

Related Questions