简体   繁体   English

C#按列表分组,然后按SUM

[英]C# group by list then SUM

How to group by then sum inside the list below is my sample code: 我如何在下面的列表中按总和进行分组是我的示例代码:

List<BrandType> brandTypeList = new List<BrandType>();

BrandType brandTypeClass = new BrandType();
brandTypeClass.Amount = 100;
brandTypeClass.Count = 50;
brandTypeClass.Category = "Fish";
brandTypeList.Add(brandTypeClass);

BrandType brandTypeClass2 = new BrandType();
brandTypeClass2.Amount = 100;
brandTypeClass2.Count = 50;
brandTypeClass2.Category = "Fish";
brandTypeList.Add(brandTypeClass2);

BrandType brandTypeClass3 = new BrandType();
brandTypeClass3.Amount = 100;
brandTypeClass3.Count = 50;
brandTypeClass3.Category = "Pork";
brandTypeList.Add(brandTypeClass3);
    brandTypeList.GroupBy(x => new { x.Category }).Select
(x => new { Category = x.Key.Category, 
Amount = x.Sum(z => z.Amount), 
Count = x.Sum(z => z.Count) });

Here's what it looks like 这是它的样子

[0] {Amount = 100, Category = "Pork", Count = 50}
[1] {Amount = 100, Category = "Fish", Count = 50}
[2] {Amount = 100, Category = "Fish", Count = 50}

How can I SUM the amout and count then group by Category? 我怎么能和的大写金额和类别再算上组? I want the result to be 我希望结果是

Amount = 200, Category = "Fish", Count = 100 数量= 200,类别=“鱼”,数量= 100

Amount = 100, Category = "Pork" Count = 50 数量= 100,类别=“猪肉”计数= 50

The following code snippet will work for you: 以下代码段将为您工作:

var result = from brand in brandTypeList
            group brand by brand.Category into grp
            select new
            {
                Category = grp.Key,
                Amount = grp.Sum(z => z.Amount),
                Count = grp.Sum(z => z.Count)
            };

This one also works fine: 这个也很好用:

var result = brandTypeList.GroupBy(x => x.Category).Select
(y => new {
    Category = y.Key,
    Amount = y.Sum(z => z.Amount),
    Count = y.Sum(z => z.Count)
});

It turns out that your code also works fine, probably the problem is that you expect list to be modified inplace, but linq does not produce side effects and new IEnumerable will be created and you need to save results to variable. 事实证明,您的代码也可以正常工作,可能的问题是您希望就地修改列表,但是linq不会产生副作用,并且会创建新的IEnumerable,并且需要将结果保存到变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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