【问题标题】:How do I get summ in Linq query?如何在 Linq 查询中获取总和?
【发布时间】:2018-10-21 22:35:03
【问题描述】:

模型是:

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]...?

【问题讨论】:

    标签: c# sql linq summary


    【解决方案1】:
    Words.Where(p => p.UsedCount.Sum(u => u.Value) > 100)
    

    这似乎就是您要查找的内容,假设您不需要明确需要排除每种语言的第一个条目以外的所有条目。

    请注意,使用 FirstOrDefault( ).Value 而不是 First( ).Value 没有什么意义 - 后者实际上会引发更有意义的异常。

    【讨论】:

      猜你喜欢
      • 2011-01-26
      • 2012-10-08
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      相关资源
      最近更新 更多