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

I just started learning linq and lambda expressions, and they seem to be well suited for finding duplicates in a complex collection of objects, but I'm a little confused and hope someone can help get me back on the road to a happy encoding.

My object is structured as list.list.uniqueCustomerIdentifier

I need to make sure that there is no duplicate of uniqueCustomerIdentifier with the whole complex object. If there are duplicates, I need to identify which duplicates and return a list of duplicates.

+3
source share
3 answers
  • Unpack hierarchy
  • Project each element into its uniqueID property
  • Group these IDs up
  • Filter groups by groups with more than 1 item
  • Project each group onto a group key (back to uniqueID)
  • List the query and save the result in the 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() 
+9
source

There is a linq Distinct () statement that allows you to filter to a specific set of records if you only need identifiers. If you set your class to override peers or you have IEqualityComparer , you can directly call the Distinct extension method to return unique results from the list. As an added bonus, you can also use Union and Intersect methods to combine or filter between two lists.

Another option is to group by id and then select the first element.

 var results = from item in list group item by item.id into g select g.First(); 
+2
source

If you want to flatten two list hierarchies, use the SelectMany method to flatten IEnumerable<IEnumerable<T>> into IEnumerable<T> .

0
source

All Articles