GoOx GoOx - 4 months ago 14
C# Question

How to combine two lists<Class> without duplicates in one of variables

I have two lists:

public class ListTemplate
{
public decimal Id { get; set; }
public string Title { get; set; }
}

public List<ListTemplate> List1 = new List<ListTemplate>();
public List<ListTemplate> List2 = new List<ListTemplate>();


List 1:

ID = 1, Title = "a"
ID = 2, Title = "b"
ID = 3, Title = "c"
ID = 4, Title = "d"


List 2:

ID = 3, Title = "c"
ID = 4, Title = "ab"
ID = 5, Title = "a"
ID = 6, Title = "a"


And I want to get result:

ID = 1, Title = "a"
ID = 2, Title = "b"
ID = 3, Title = "c"
ID = 4, Title = "ab"
ID = 5, Title = "a"
ID = 6, Title = "a"


We see, title item was replaced using item from list2.

Propably the best way to get such a result will be used LINQ. Does someone know a hot way to do this?

Answer

Since you have omitted ID = 4, Title = "d" from the first list i assume that you want to take all items from list1 + list2 and if an ID exists in both lists take the one from the second list.

Then this approach using Except + Concat works:

var idOnlyList1 = List1.Select(x => x.Id).Except(List2.Select(x => x.Id));
var templates1 = from id in idOnlyList1 join lt1 in List1 on id equals lt1.Id select lt1;
List<ListTemplate> result = templates1.Concat(List2).ToList();
Comments