[英]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.
我做了一些搜索,但没有任何结果可以帮助我实现所需的 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如果我正在寻找最近 1000 的总购买价格,我应该得到
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然后,您可以使用
TakeWhile
来获取项目,直到达到某些条件
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.或者您可以通过创建中间值对在一个 go 中完成所有操作。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.