Tuesday 20 April 2010

Finding Duplicates in a list using LINQ Lambda Expressions

Here is a one-liner that allows you to get a list of the duplicates in a list. I originally tried to approach the problem using the LINQ Group By syntax (like what I did here in 2008), but I found this to be a much simpler solution.

This works by utilizing the .Except extension method that compares with a blank list. Because ALL items don't match what is in the blank list, then all elements are passed to the subsequent .Any statement which picks up any item in which all fields specified in the lambda expression match.

Here's the code for listing duplicates in LINQ, comparing against multiple columns:

var duplicates =
timesheetDto.TimesheetItems.Where(timesheetItem =>
.Except(new List { timesheetItem })
.Any(matchingTimesheetItem => 
timesheetItem.ActivityType  == matchingTimesheetItem.ActivityType &&
timesheetItem.ReceivingWBSElement == matchingTimesheetItem.ReceivingWBSElement &&
timesheetItem.ReceivingCostCentre == matchingTimesheetItem.ReceivingCostCentre &&
timesheetItem.SendingCostCentre == matchingTimesheetItem.SendingCostCentre

return duplicates.Count > 0;

1 comment:

Chanveda said...

Brilliant, thats very useful bit of code. Thanks