Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two IEnumerable with LINQ

Tags:

c#

.net

linq

I've got the following class

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

    public int Version { get; set; }

    (...)
}

And I have the following IEnumerable<Application>:

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

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

How can I merge them into a single IEnumerable<Application> using LINQ while ensuring that if two Applications have the same Id only the one with the highest Version is added to the new IEnumerable<Application>, effectively my final `IEnumerable should be equivalent to:

IEnumerable<Application> final = new List<Application>
{
    new Application {Id = 1, Version = 2},
    new Application {Id = 2, Version = 1},
    new Application {Id = 3, Version = 3},
    new Application {Id = 4, Version = 1}
}
like image 761
cogumel0 Avatar asked Nov 03 '25 16:11

cogumel0


2 Answers

You can use GroupBy combined with selecting maximum in group via Aggregate:

IEnumerable<Application> final = applications1
    .Concat(applications2)
    .GroupBy(a => a.Id)
    .Select(g => g.Aggregate((acc, curr) => acc.Version > curr.Version ? acc: curr))
    .ToList();
like image 123
Guru Stron Avatar answered Nov 06 '25 07:11

Guru Stron


A more procedural way would be:

var concat = applications1.Concat(applications2)
    .ToArray();

var final = concat
    .GroupBy(a => a.Id)
    .Select (g => new
    {
        ApplicationId = g.Key,
        MaxVersion = g.Max(i => i.Version)
    })
    .Select(i => concat.FirstOrDefault(
        existing => existing.Id == i.ApplicationId && 
                    existing.Version == i.MaxVersion))
    .ToList();
like image 36
Rubens Farias Avatar answered Nov 06 '25 09:11

Rubens Farias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!