Search code examples
c#linqvisual-studio-2013distinct-valuesmorelinq

morelinq distinct by multiple properties


I have been using morelinq to create a distinct list of objects. My objects have about 20 properties, none of which will be unique in the final list. However 2 properties used together can reveal the unique objects:

Parent Id | Child Id

  • 1 | 1
  • 1 | 2
  • 2 | 1
  • 2 | 2
  • 2 | 3

I saw this question and thought it was the same problem so I downloaded morelinq and tried using:

list = list.DistinctBy(c => new { c.id, c.parentid }).ToList();

However this results in a distinct list on EITHER property, not both (so I'd only ever see one child per parent)

What is the correct way to use morelinq to achieve this?


Solution

  •     list = list
               .GroupBy(a=> new { a.id, a.parentid})
               .Select(a=> a.first());