0

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; }
}
5
  • 1
    Please provide information about the structure of data you're working with. Commented Sep 27, 2015 at 12:43
  • @DmytroShevchenko, foo has many bars (List<Bar>) and bars has many qux (List<Qux>). Qux have two properties (size and hash). Commented Sep 27, 2015 at 12:46
  • foo.SelectMany() does not make sense, since foo is not a collection. Commented Sep 27, 2015 at 12:53
  • @DmytroShevchenko, thanks edited the question. Commented Sep 27, 2015 at 12:55
  • The type of size should be int, not string. Commented Sep 27, 2015 at 12:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.