Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two lists on a given property

Tags:

c#

linq

I have two queries, each one returning a list of objects.

List<A> list1 = (....query...)
List<A> list2 = (....query...)

"A" is an object model.

Both queries return almost the same objects but with different properties set.

I want to remove duplicates merge them into a single list based on a property of object A.

Basically something like this:

List<A> finalLis = list1 join list2 on elemList1.somePropID == elemList2.somePropID 

In simple C# style it would be something like this:

foreach(elem1 : list1) {
    foreach(elem2: list1) {
       if(elem1.someID == elem2.someID) {
           elem1.someProp = elem2.someProp
           elem1.otherProp = elem2.otherProp
        }
     }
}

I don't want to do it in this way because I'm sure there's a more elegant way in linq.

If you have any suggestions please let me know.

like image 472
cmg Avatar asked Nov 13 '22 13:11

cmg


1 Answers

Linq can help you with selecting but not with updating. So you won't get rid of foreach statement. So your task could be written with linq like this:

//the query is like LEFT JOIN in SQL
var query = from x in list1
            join y in list2 on x.IDItem equals y.IDItem
            into z
            from q in z.DefaultIfEmpty()
            select new {IOne = x, ITwo = q};
foreach (var pair in query)
{
    if (pair.ITwo != null) // && pair.IOne.OneProperty != null
        pair.IOne.OneProperty = pair.ITwo.TwoProperty;
}

var resultList = query.Select(x => x.IOne).ToList();

You can check the results here.

like image 52
mipe34 Avatar answered Nov 15 '22 06:11

mipe34