如何在Linq查询中获取汇总?

时间:2018-10-21 22:35:04

标签: c# sql linq summary

模型是:

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; }
}

有语言列表:

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

单词列表

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

我计算每种语言在每个单词中使用了多少次。 我需要使所有单词总共使用超过100次,而与哪种语言无关:

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)

如何使它更简单并避免手动编写langList [0],langList [1] ...?

1 个答案:

答案 0 :(得分:2)

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

假设您不需要明确排除每种语言的第一个条目,那么您似乎正在寻找它。

请注意,在FirstOrDefault( ).Value上使用First( ).Value几乎没有意义-后者实际上会引发更有意义的异常。

相关问题