I need to remove duplicate elements where the two parameters are equal. It was possible to remove elements where only one parameter ( Id ) is repeated, here is the code:

 var items = items.GroupBy(x => x.Id).Select(group => group.OrderBy(x => x.Date).First()).ToList(); 

This is an input list:

 Id: 1, Type: 2, Date: 12.02.2018 Id: 1, Type: 2, Date: 15.02.2018 Id: 1, Type: 1, Date: 19.02.2018 Id: 2, Type: 2, Date: 12.02.2018 

The output should be:

 Id: 1, Type: 2, Date: 12.02.2018 Id: 1, Type: 1, Date: 19.02.2018 Id: 2, Type: 2, Date: 12.02.2018 

How to remove duplicate elements from the list, where Id and Type are equal?

  • Comments are not intended for extended discussion; conversation moved to chat . - Yuriy SPb
  • Possible duplicate question: How to group by several fields? - 0xdb
  • @ 0xdb never duplicate. The question you have cited speaks of a more complicated case - grouping by a dynamic list of fields. Immediately fields for grouping are known in advance. - Pavel Mayorov

1 answer 1

Use an anonymous class:

 items = items.GroupBy(x => new { x.Id, x.Type }) .Select(a => a.OrderBy(x => x.Date).First()) .ToList(); 

Or tuple (C # 7.0+):

 items = items.GroupBy(x => (x.Id, x.Type)) .Select(a => a.OrderBy(x => x.Date).First()) .ToList();