Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for duplicates in a complex object using Linq or Lambda expression

I've just started learning linq and lambda expressions, and they seem to be a good fit for finding duplicates in a complex object collection, but I'm getting a little confused and hope someone can help put me back on the path to happy coding.

My object is structured like list.list.uniqueCustomerIdentifier

I need to ensure there are no duplicate uniqueCustomerIdentifier with in the entire complex object. If there are duplicates, I need to identify which are duplicated and return a list of the duplicates.

like image 365
Loscas Avatar asked Dec 23 '22 14:12

Loscas


1 Answers

  • Unpack the hierarchy
  • Project each element to its uniqueID property
  • Group these ID's up
  • Filter the groups by groups that have more than 1 element
  • Project each group to the group's key (back to uniqueID)
  • Enumerate the query and store the result in a list.

var result = 
  myList
    .SelectMany(x => x.InnerList)
    .Select(y => y.uniqueCustomerIdentifier)
    .GroupBy(id => id)
    .Where(g => g.Skip(1).Any())
    .Select(g => g.Key)
    .ToList()
like image 175
Amy B Avatar answered May 23 '23 09:05

Amy B