Search code examples
c#sqllinqsummary

How do I get summ in Linq query?


The models are:

public class Word
{
    public int Id { get; set; }
    public IList<UsedCount> UsedCount { get; set; }
}

public class UsedCount
{
    public int Id { get; set; }
    public string Key { get; set; }
    public int Value { get; set; }
}

There is the list of languages:

// Actually there are more then 3 langs used
List<string> langList = new List<string> { "en", "pl", "de" }; 

And the list of words

List<Word> words = new List<Words>();

I count how much times each word used in each languages. I need to get all words used more then 100 times in total, doesn't matter in which language:

renewingIteration = Words.Where(p => (
    p.UsedCount.FirstOrDefault(count => count.Key == langList[0]).Value +
    p.UsedCount.FirstOrDefault(count => count.Key == langList[1]).Value +
    p.UsedCount.FirstOrDefault(count => count.Key == langList[2]).Value 
    //... and so on
    > 100)

How can I make it simpler and escape writing langList[0], langList[1]... manually?


Solution

  • Words.Where(p => p.UsedCount.Sum(u => u.Value) > 100)
    

    Would seem to be what you're looking for, assuming that you don't explicitly need to exclude all but the first entry for each language.

    Note that there's little point using FirstOrDefault( ).Value over First( ).Value - the latter will actually throw a more meaningful exception.