LINQ, simplifying expression - take while sum of taken does not exceed given value

前端 未结 5 1205
别那么骄傲
别那么骄傲 2021-01-04 03:50

Given a setup like this ..

class Product {
   int Cost;
   // other properties unimportant
}

var products = new List {
    new Product { Cost         


        
5条回答
  •  情歌与酒
    2021-01-04 04:10

    You can do this if you want a solution without an external variable

    var indexQuery = products.Select((x,index) => new { Obj = x, Index = index });
    
    var query = from p in indexQuery 
                let RunningTotal = indexQuery.Where(x => x.Index <= p.Index)
                                             .Sum(x => x.Obj.Cost)
                where credit >= RunningTotal
                select p.Obj;
    

提交回复
热议问题