英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论