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

后端 未结 2 1652
失恋的感觉
失恋的感觉 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 06:15

    You just create a variable to hold the sum, then add to it as each item in the list is tested with the where clause:

    int sum = 0;
    from product in list where (sum += product.Quantity) < 8 select product
    

提交回复
热议问题