Linq: How to query items from a collection until the sum reaches a certain value

后端 未结 2 1654
失恋的感觉
失恋的感觉 2020-12-06 05:24

Given the following object:

public class Product {
   string Name {get;} 
   int Quantity {get;}
}

using Linq, how would I query a Li

2条回答
  •  时光说笑
    2020-12-06 05:52

    Here is a quick 2 liner.

    var sum = 0;
    var query = col.Where(x => { var temp = sum; sum += x.Quantity; return temp < 500; });
    

    Replace 500 with the constant or variable of your choosing.

    EDIT

    Here is mquander's more efficient solution

    var sum = 0;
    var query = col.TakeWhile(x => { var temp = sum; sum += x.Quantity; return temp < 500; });
    

提交回复
热议问题