I have a List<>
of custom objects. This custom type has a property called Name
which should be unique among the list. In other words, no 2 items items in the list should have the same value for their Name
property.
When I validate this list, I want to retrieve the offending items. Is there a Linq operation which will allow me to do this?
I want to have something like
listOfItems.Where(x => x.Name.Equals(/*anything else in this list with the same value for name */)
Basically, I am trying to avoid checking the entire list against every item in the list (in a nested foreach):
private IList<ICustomObject> GetDuplicatedTypeNames(IList<ICustomObjects> customObjectsToFindDuplicatesIn)
{
var duplicatedList = new List<ICustomObject>();
foreach(var customObject in customObjectsToFindDuplicatesIn)
foreach(var innerCustomObject in customObjectsToFindDuplicatesIn)
if (customObject == innerCustomObject && customObject .Name.Equals(innerCustomObject.Name))
duplicatedList.Add(customObject);
return duplicatedList;
}
(EDIT) NOTE: I am constrained to using a List<> by domain rules and using a Dictionary<> is not an option.