Remove duplicates while merging lists using Union in LINQ

后端 未结 4 1927
野趣味
野趣味 2021-01-17 13:48

I am trying to merge two lists using list.Union in LinqPad but I can\'t get it to work and wanted to check my understanding is correct.

Giv

4条回答
  •  清酒与你
    2021-01-17 13:58

    You can create a class implementing

    IEqualityComparer
    

    Is this class define Equals and GetHashCode After it you can pass this comparer to you Union method Just like that:

    public class MyComparer:IEqualityComparer{
    //Equals and GetHashCode
    }
    
    var mergedList = list.Union(list2, new MyComparer()).ToList();
    

提交回复
热议问题