LINQ多个group by然后按值计数得到第一个组

时间:2016-12-26 12:45:31

标签: c# asp.net asp.net-mvc linq group-by

我有一个像以下一样的linq查询:

var _transactionsList = TransactionsData
                .GroupBy(x => new { x.ItemID, x.Title, x.GalleryURL })
                .Select(pr => new TransactionsTabResults
                {
                    ItemID = pr.Key.ItemID,
                    Title = pr.Key.Title,
                    GalleryURL = pr.Key.GalleryURL,

                    ItemPrice = pr.OrderByDescending(a => a.TransactionDate).First().ItemPrice,

                    TotalSoldItems = pr.Count(),
                    TotalRevenuePerItem = pr.Sum(y => y.ItemPrice),
                    AveragePrice = pr.Average(y => y.ItemPrice),
                }).ToList();

我正在尝试通过将其分组来获取总销售商品值:

ItemID    Sales    ItemName

1          1         Item1
1          3         Item1
1          5         Item1
1          6         Item1
2          2         Item2
2          2         Item2
2          2         Item2
2          2         Item2

所需的输出是:

ItemID   Sales   ItemName
1         15       Item1
2         8        Item2

我写的上面的查询通过说:

给出了总销售额的错误值
 TotalSoldItems = pr.Count(),

我如何计算或总结一个具有唯一ID的项目的销售额(这是我所分组的)......

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你正在以错误的方式使用GroubBy。您每次都创建新的唯一对象。因此,.GroupBy(x => new { x.ItemID, x.Title, x.GalleryURL }).Select(x => new { Key = new { x.ItemID, x.Title, x.GalleryURL}, Value =x })表示相同的

如果您需要唯一身份证明,则按ID进行分组

TransactionsData
.GroupBy(x => x.ItemID)
.Select(pr => new TransactionsTabResults
{
    ItemID = pr.Key,
    Title = pr.First().Title,
    GalleryURL = pr.First().GalleryURL,
    ItemPrice = pr.OrderByDescending(a => a.TransactionDate).First().ItemPrice,
    TotalSoldItems = pr.Count(),
    TotalRevenuePerItem = pr.Sum(y => y.ItemPrice),
    AveragePrice = pr.Average(y => y.ItemPrice),
}).ToList();

<强>建议

优化您的LINQ。您正在多次迭代集合。这是建议的代码:

TransactionsData
.GroupBy(x => x.ItemID)
.Select(pr => 
{
    var items = x.pr.ToArray;
    var sum = items.Sum(y => y.ItemPrice);
    return new TransactionsTabResults
    {
        ItemID = pr.Key,
        Title = items[0].Title,
        GalleryURL = items[0].GalleryURL,
        ItemPrice = pr.Aggregate((max, cur)=>max.TransactionDate<cur.TransactionDate?cur:max).ItemPrice,
        TotalSoldItems = items.Length,
        TotalRevenuePerItem = sum,
        AveragePrice = sum/items.Length,
    };
}).ToList();