简体   繁体   中英

Linq query to select records based on most recent sum

I'm writing a method that selects customer records based on a group by with the most recent purchase total equal (passed to the method). I did some search and nothing showed up that helps me to achieve the desired output.

 customerList.GroupBy(x=> x.CustomerID },
                      (key, result) =>
                      {
                       var orderedList = result.OrderByDescending(c => c.Date).ToList();

                      return new Customer
                      {
                          CustomerID = orderedList.First().CustomerID,
                          PurchaseID = orderedList.First().PurchaseID,
                          Price = orderedList.First().Price,
                     };
                   });
CUSTOMERID PURCHACEID PRICE DATE
1 11 235 01-03-2021
1 12 230 01-03-2021
1 14 235 05-04-2021
1 15 535 06-04-2021
1 16 230 07-04-2021

If I'm looking for most recent total purchase price of 1000, I should get

CUSTOMERID PURCHACEID PRICE DATE
1 14 235 05-04-2021
1 15 535 06-04-2021
1 16 230 07-04-2021

You probably need to produce a separate list with the cumulative sums . You can then use TakeWhile to take items until some condition is reached

var list = new[] { 1, 2, 3, 4, 5 };
var sum = 0;
var cummulativeSums = list.Select(v => sum += v).ToList();
var result= list.TakeWhile((_, index) => cummulativeSums[index] < 7).ToList();
// 1, 2, 3

Or you could do it all in one go by creating intermediate pair of values.

var list = new[] { 1, 2, 3, 4, 5 };
var sum = 0;
var result = list.Select(value => (sum += value, value))
    .TakeWhile(pair => pair.Item1 < 7)
    .Select(pair => pair.value)
    .ToList();

         

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM