LINQ,简化表达式-取时取和不超过给定值 [英] LINQ, simplifying expression - take while sum of taken does not exceed given value
本文介绍了LINQ,简化表达式-取时取和不超过给定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出这样的设置..
class Product {
int Cost;
// other properties unimportant
}
var products = new List<Product> {
new Product { Cost = 5 },
new Product { Cost = 10 },
new Product { Cost = 15 },
new Product { Cost = 20 }
};
var credit = 15;
假设列表将按照给定的顺序排序.我希望基本上遍历列表中的每个项目,保持成本的总和,并在总成本不超过credit
的情况下继续推出产品.
Assume that the list will be sorted in the given order. I wish to basically iterate over each item in the list, keep a summed value of cost, and keep getting products out as long as the total cost does not exceed credit
.
我可以使用一些循环和东西来做到这一点,但是我想知道是否有一种方法可以将其压缩为一个更简单的LINQ查询.
I can do this with some loops and stuff, but I was wondering if there is a way to compact it into a simpler LINQ query.
推荐答案
不是完全" linq,因为它需要一个额外的变量,但这是我最容易想到的:
Not "fully" linq, because it needs one extra variable, but it is the easiest I could think of:
int current=0;
var selection = products.TakeWhile(p => (current = current + p.Cost) <= credit);
这篇关于LINQ,简化表达式-取时取和不超过给定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文