如何按多个属性汇总列表

huangapple go评论89阅读模式
英文:

How summarize list by mutiple property

问题

我想要通过相同的 "Typ" 和 "Name" 来汇总它,或者甚至可以通过除了 "Amount" 之外的更多相同属性来汇总。我该如何做?

英文:

i have a list like:

List<ClassName> item= new List<ClassName>();
list.Add(new ClassName()
{
    Typ= 1,
    Name= A,
    Amount = 5
});
list.Add(new ClassName()
{
    Typ= 2,
    Name= B,
    Amount = 3
});
list.Add(new ClassName()
{
    Typ= 1,
    Name= A,
    Amount = 3
});
list.Add(new ClassName()
{
    Typ= 1,
    Name= C,
    Amount = 3
});

I want to summarize it by the same Typ and Name, or maybe by even more same properties besides Amount. How can i do it?

答案1

得分: 1

你可以使用LINQ中的'Group By'来实现它。

var summarizedList = list.GroupBy(item => new { item.Typ, item.Name }) 
            .Select(group => new ClassName
            {
                Typ = group.Key.Typ,
                Name = group.Key.Name,
                Amount = group.Sum(item => item.Amount)
            })
            .ToList();
英文:

you can do it by 'Group By' in LINQ.

 var summarizedList = list.GroupBy(item => new { item.Typ, item.Name }) 
            .Select(group => new ClassName
            {
                Typ = group.Key.Typ,
                Name = group.Key.Name,
                Amount = group.Sum(item => item.Amount)
            })
            .ToList();

huangapple
  • 本文由 发表于 2023年8月10日 15:20:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定