我可以有一个LINQ查询,计算用属性上的位置过滤的行总数
本文关键字:位置 过滤 属性 LINQ 有一个 查询 计算 我可以 | 更新日期: 2023-09-27 18:14:26
我有一个包含如下数据的数组:
var arr =
[{count=0, instances=1},
{count=1, instances=2},
{count=3, instances=1},
{count=4, instances=5},
{count=5, instances=2}]
是否有可能使用LINQ为我创建一个查询,如果我要指定计数,将显示实例的总数?
So for example if I did a query with 1 it would give me 3 (from 1+2)
So for example if I did a query with 4 it would give me 9 (from
1+2+1+5)
var countToTake; // 0 < countToTake <= arr.Length
var instanceCount = arr.Take(countToTake).Sum(item => item.instances)
编辑:见注释
var instanceCount = arr.Take(arr.IndexOf(item => item.count == countToTake)).Sum(item => item.instances)
var sum = arr.Where(x => x.count <= maxCount).Select(x => x.instances).Sum();
下面的代码就可以了
int selectedCount = 4 //hardcoded for illustration purpose, you will set this programatically
int sum = arr.Where(x => arr.IndexOf(x) <= (arr.FindIndex(i => i.count.Equals(selectedCount))))
.Select(x => x.instances).Sum();