代码之家  ›  专栏  ›  技术社区  ›  mr_blond

如何在Linq查询中获取Summ?

  •  0
  • mr_blond  · 技术社区  · 7 年前

    模型是:

    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 回复  |  直到 7 年前
        1
  •  2
  •   Dylan Nicholson    7 年前
    Words.Where(p => p.UsedCount.Sum(u => u.Value) > 100)
    

    似乎是您正在寻找的,假设您不需要显式地排除每种语言的所有条目,除了第一个条目。

    注意,使用 FirstOrDefault( ).Value 结束 First( ).Value -后者实际上会抛出一个更有意义的异常。