LINQ:如何从一个集合查询项目,直到总和达到一定值 [英] Linq: How to query items from a collection until the sum reaches a certain value
问题描述
由于下列对象:
public class Product {
string Name {get;}
int Quantity {get;}
}
使用LINQ,我将如何查询列表与LT;产品>
,直到我得到了一笔> =
一个给定的量是多少?换句话说,如果我的名单看起来像
using Linq, how would I query a List<Product>
until I got a sum >=
a given quantity? In other words, if my list looked like
Name Quantity
-----------------
prod1 5
prod2 6
prod7 7
我要查询的列表和拉实例,直到我得到一个总> = 8
。在这种情况下,我会得到该列表中的前两个项目。如果我想总和方式> = 12
,我会得到所有三个
I want to query the List and pull instances until I get a Sum >=8
. In this case I'd get the first two items in the List. If I wanted sum >= 12
, I'd get all three.
我知道我可以写一循环做到这一点对我来说,但我幻想着有使用LINQ来实现同样的事情,一些华而不实的单行。
I know I can write a loop to do this for me, but I was fantasizing that there was some slick one-liner using Linq to achieve the same thing.
感谢
推荐答案
下面是一个快速的2班船。
Here is a quick 2 liner.
var sum = 0;
var query = col.Where(x => { var temp = sum; sum += x.Quantity; return temp < 500; });
替换500与您所选择的固定或可变。
Replace 500 with the constant or variable of your choosing.
修改
下面是mquander的更有效的解决方案。
Here is mquander's more efficient solution
var sum = 0;
var query = col.TakeWhile(x => { var temp = sum; sum += x.Quantity; return temp < 500; });
这篇关于LINQ:如何从一个集合查询项目,直到总和达到一定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!