问题
suppose I have a list that comes from a database like this:
List<Item> list =
{
new Item
{
TypeID = 2,
Count = 5
},
new Item
{
TypeID = 2,
Count = 7
},
new Item
{
TypeID = 5,
Count = 2
}
};
I would like to sum up all elements with the same TypeID
so that I have a final result list with two elements only:
List<Item> list =
{
new Item
{
TypeID = 2,
Count = 12
},
new Item
{
TypeID = 5,
Count = 2
}
};
How can I achive this using LINQ?
Cheers
Simon
回答1:
You can use GroupBy
to group by TypeID
first and then do Sum
on each group:
var result = list.GroupBy(x => x.TypeID)
.Select(g => new Item() {
TypeId = g.Key,
Count = g.Sum(x => x.Count)
})
.ToList();
回答2:
list.GroupBy(x=>x.TypeID)
.Select(x=>new Item(){TypeID=x.Key,Count=x.Sum(y=>y.Count) })
.ToList();
回答3:
Linq extension method Union.
var mergedList = list1.Union(list2).ToList();
来源:https://stackoverflow.com/questions/12637448/combining-elements-in-the-same-list