Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge items in list with the same key/property

Tags:

c#

merge

list

linq

This shouldn't be very hard to do but I'm struggling to find out the correct way to do this.

I have two lists that have the same properties. What I would like to do is merge these two lists together and combine/merge the individual items in the lists that have the same key/property.

Here is my ViewModel:

public class GradeViewModel {
    public int GradeId { get; set; }
    public string Name { get; set; }
    public int Total { get; set; }
}

And here I am populating my lists:

var buyPostGrades = Mapper.Map<IEnumerable<BuyPostGrade>, IEnumerable<GradeViewModel>>(_reportService.GetBuyPostGrades());
var sellPostGrades = Mapper.Map<IEnumerable<SellPostGrade>, IEnumerable<GradeViewModel>>(_reportService.GetSellPostGrades());

Now what I would like to do is combine the two lists together into one and if there are any items between the lists that share the same GradeId then I want to merge them into just one item.

So, for example, if I had an item in my buyPostGrades list that looked like the following:

GradeId = 6,
Name = "TestGrade",
Total = 4

and then I had an item in my sellPostGrades list that looked like the following:

GradeId = 6,
Name = "TestGrade",
Total = 10

then I would like to merge those two items into one that would look like:

GradeId = 6,
Name = "TestGrade",
Total = 14

I'm sure there in some Linq that I can use to do this but I'm still new to it and am not sure which way would be best.

like image 275
Quiver Avatar asked Oct 27 '25 18:10

Quiver


1 Answers

Assuming that identical grade ID implies identical name, you can merge two lists as follows:

var res buyPostGrades
    .Concat(sellPostGrades)
    .GroupBy(x => new {x.GradeId, x.Name})
    .Select(g => new GradeViewModel {
        GradeId = g.Key.GradeId
    ,   Name = g.Key.Name
    ,   Total = g.Sum(x => x.Total)
    }).ToList();
like image 139
Sergey Kalinichenko Avatar answered Oct 30 '25 07:10

Sergey Kalinichenko