Search code examples
c#.netlinqlistienumerable

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

  • 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();