[英]How can I use LINQ to get a property matching a conditional sum?
Ok, I get the title sounds weird, but here's my scenario. 好的,标题听起来很奇怪,但这是我的情况。 I think ts a simple query, but its hard to explain on paper. 我认为这是一个简单的查询,但是很难在纸上解释。 And I'm having trouble with the LINQ myself. 我自己在使用LINQ时遇到了麻烦。 Best to explain by example: 最好用例子来解释:
I have a list of objects (in psuedocode) that looks like: 我有一个类似psuedocode的对象列表:
var data = [
{
quantity: 123,
rate: 0.12
},
{
quantity: 456,
rate: 0.13
},
{
quantity: 3,
rate: 0.14
},
{
quantity: 92,
rate: 0.15
}
]
I am trying to generate a LINQ query that returns rate
equaling the total sum of an input quantity. 我正在尝试生成一个LINQ查询,该查询返回的rate
等于输入数量的总和。
Explaination by example: 举例说明:
Using the example data above, I want to find the rate
that matches a total quantity of 581
(a variable input from elsewhere). 使用上面的示例数据,我想找到与581
(从其他位置输入的变量)总量相匹配的rate
。 The first three objects in my list have quantities that total 582, so I want my LINQ query to return 0.14
(the rate
matching the condition that the total quantity
fields is greater than my input quantity). 列表中的前三个对象的总数量为582,因此我希望我的LINQ查询返回0.14
(与总quantity
字段大于输入数量的条件匹配的rate
)。
I should be able to use LINQ to do this, right? 我应该能够使用LINQ来做到这一点,对吧? Its sort of a .Sum
and a .Where
, and that's where I'm getting confused. 它有点像.Sum
和.Where
,这就是我感到困惑的地方。
Are there any references out that to address this type of scenario? 有没有参考资料可以解决这种情况? Does anyone have any experience writing a "conditional sum"? 有没有人写过“有条件的和”的经验?
In functional programming, this would be a variation of a reduce
. 在函数式编程中,这将是reduce
的变体。 In LINQ, the Aggregate
method can be used for this purpose. 在LINQ中, Aggregate
方法可用于此目的。 Psuedo-LINQ: 伪LINQ:
var limit = 581;
var rate = data.Aggregate((acc, cur) =>
{
if (acc.quantity < limit)
{
return new
{
quantity = acc.quantity + cur.quantity,
rate = cur.rate
};
}
else
{
return acc;
}
}).rate;
EDIT: A more compact, one-line version: 编辑:更紧凑的单行版本:
var rate = data.Aggregate((acc,cur) => acc.quantity < limit ? new { quantity = acc.quantity + cur.quantity, rate = cur.rate } : acc).rate;
Was going for Aggregate
but failed to get in one line :( 本来要Aggregate
但未能进入一行:(
For the desired of one-liner , this is a funny usage of LINQ
:) 对于单线的需求 ,这是LINQ
的有趣用法:)
var target = 581;
var sum = 0;
var rate = data.First(i =>(sum += i.Quantity) > target).Rate; // 0.14
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.