'Union two list by property
I would like to merge two list without duplicates. It should distinct only by one property.
I have a class:
public class Test
{
public int Id { get; set; }
public string Prop { get; set; }
public string Type { get; set; }
}
I have two lists which I would like to merge without duplicates by Type. So, firstly I want to take everything from list 1 and then from list 2 when Type doesn't exist in list 1.
I've tried union.
Solution 1:[1]
You've to use IEqualityComparer. See at : https://msdn.microsoft.com/en-us/library/ms132151%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
class Compare : IEqualityComparer<Test>
{
public bool Equals(Test x, Test y)
{
return x.Id == y.Id;
}
public int GetHashCode(Test codeh)
{
return codeh.Id.GetHashCode();
}
}
Then use
var union = list1.Union(list2).Distinct(new Compare()).ToList();
Solution 2:[2]
Using .NET 6 or higher, you can use the UnionBy() method which will merge 2 lists excluding duplicates by a property :
var mergedLists = firstList.UnionBy(secondList, u => u.property).ToList();
For more informations : Microsoft doc
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | M.S. |
Solution 2 | twllm_dvlp |