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 => timesheetDto.TimesheetItems .Except(new List{ timesheetItem }) .Any(matchingTimesheetItem => timesheetItem.ActivityType == matchingTimesheetItem.ActivityType && timesheetItem.ReceivingWBSElement == matchingTimesheetItem.ReceivingWBSElement && timesheetItem.ReceivingCostCentre == matchingTimesheetItem.ReceivingCostCentre && timesheetItem.SendingCostCentre == matchingTimesheetItem.SendingCostCentre ) ).ToList(); return duplicates.Count > 0;
1 comment:
Brilliant, thats very useful bit of code. Thanks
Post a Comment