Remove duplicates while merging lists using Union in LINQ

后端 未结 4 1928
野趣味
野趣味 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 14:13

    You can try something like that if not happy with default comparer (which is, in turn, utilizes GetHashCode method as @IlyaIvanov had mentioned):

    // get all items that "other than in first list", so Where() and Any() are our filtering expressions
    var delta = list2.Where(x2 => !list.Any(x1 => (x1.Id == x2.Id) && (x1.field1 == x2.field1)));
    
    // now let merge two enumerables that have nothing "equal" between them
    var merged = list.Union(delta).ToList();
    

提交回复
热议问题