K K
K K

Reputation: 41

Merge two list in C# based on a condition

I have two lists based on the class

public class test
{
    public string id { get; set; }
    public Int32 quantity { get; set; }
}

List1 
{"A", 1}
{"B", 2}
{"C", 3}

List2
{"A", 1}
{"B", 4}
{"D", 5}

The merged list needs to include all the items from both the list and if the same id occurs in both the lists, then the quantity should be compared and the one with greater quantity should be selected. The merged list needs to be

Merged list
{"A", 1}
{"B", 4}
{"C", 3}
{"D", 5}

order of the items in the list is not important.

How to implement this merge.

Upvotes: 3

Views: 7817

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500865

You could use something like:

var query = list1.Concat(list2)
                 .GroupBy(x => x.id)
                 .Select(g => g.OrderByDescending(x => x.quantity).First())
                 .ToList();

It's not nice, but it would work. (This approach avoids creating a new instance of test as lc.'s answer does. I don't know whether that's important to you, but I can see it being important in some scenarios.)

It does assume that if an ID occurs more than once in either of the lists, that you still only want it to be returned once in the result.

Alternatively, using MaxBy from MoreLINQ:

var query = list1.Concat(list2)
                 .GroupBy(x => x.id)
                 .Select(g => g.MaxBy(x => x.quantity))
                 .ToList();

Upvotes: 10

lc.
lc.

Reputation: 116498

Assuming "ID" should always be unique:

var list = (from l in List1.Concat(List2)
           group l by l.id into g
           select new test() {id = g.Key, quantity = g.Max(x=>x.quantity)})
           .ToList();

Upvotes: 8

Related Questions