Search code examples
c#linqmergeienumerable

Merge 3 IEnumerable<Application> lists into one


I have simplified my problem

public class Application
{
    public int Id { get; set; }
    public int Version { get; set; }
    public int Status { get; set; }
}

My 3 lists:

IEnumerable<Application> applications1 = new List<Application>
{
    new Application {Id = 1, Version = 1, Status = 1},
    new Application {Id = 2, Version = 1, Status = 1},
    new Application {Id = 3, Version = 3, Status = 1}
};

IEnumerable<Application> applications2 = new List<Application>
{
    new Application {Id = 1, Version = 2, Status = 2},
    new Application {Id = 2, Version = 2, Status = 2},
    new Application {Id = 3, Version = 1, Status = 0}
};

IEnumerable<Application> applications3 = new List<Application>
{
    new Application {Id = 1, Version = 5, Status = 1},
    new Application {Id = 2, Version = 0, Status = 1},
    new Application {Id = 3, Version = 6, Status = 1}
};

I want to produce this:

IEnumerable<Application> applications4 = new List<Application>
{
    new Application {Id = 1, Version = 5, Status = 2},
    new Application {Id = 2, Version = 2, Status = 2},
    new Application {Id = 3, Version = 6, Status = 1}
};

I.e. one list with the highest value of Version and Status. I have tried with LINQ but I don't get it.

My best is this, but it just gets the highest version. I don't understand how I do when there are 2 properties to select from:

IEnumerable<Application> applications4 = applications1
    .Concat(applications2)
    .Concat(applications3)
    .GroupBy(a => a.Id)
    .Select(g => g.Aggregate((acc, curr) => acc.Version > curr.Version ? acc: curr ))
    .ToList();

Solution

  • You should use the Max() to get the max values from the grouped properties.

    IEnumerable<Application> applications4 = applications1
        .Concat(applications2)
        .Concat(applications3)
        .GroupBy(a => a.Id)
        .Select(g => new Application
                {
                    Id = g.Key,
                    Version = g.Max(x => x.Version),
                    Status = g.Max(x => x.Status)
                })
        .ToList();