如何在 Linq 查询中获取总和?
How do I get summ in Linq query?
模型是:
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]...?
Words.Where(p => p.UsedCount.Sum(u => u.Value) > 100)
这似乎是您要查找的内容,假设您没有明确需要排除每种语言的第一个条目以外的所有条目。
请注意,在 First( ).Value
上使用 FirstOrDefault( ).Value
没有什么意义 - 后者实际上会抛出一个更有意义的异常。
模型是:
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]...?
Words.Where(p => p.UsedCount.Sum(u => u.Value) > 100)
这似乎是您要查找的内容,假设您没有明确需要排除每种语言的第一个条目以外的所有条目。
请注意,在 First( ).Value
上使用 FirstOrDefault( ).Value
没有什么意义 - 后者实际上会抛出一个更有意义的异常。