I have a List<> of objects in C# and I need a way to return those objects that are considered duplicates within the list. I do not need the Distinct resultset, I need a
My answer takes inspiration (in this order) from the followers respondents: Joe Coehoorn, Greg Beech and Jon Skeet.
I decided to provide a full example, with the assumption being (for real word efficiency) that you have a static list of car colors. I believe the following code illustrates a complete solution to the problem in an elegant, although not necessarily hyper-efficient, manner.
#region SearchForNonDistinctMembersInAGenericListSample
public static string[] carColors = new[]{"Red", "Blue", "Green"};
public static string[] carStyles = new[]{"Compact", "Sedan", "SUV", "Mini-Van", "Jeep"};
public class Car
{
public Car(){}
public string Color { get; set; }
public string Style { get; set; }
}
public static List SearchForNonDistinctMembersInAList()
{
// pass in cars normally, but declare here for brevity
var cars = new List(5) { new Car(){Color=carColors[0], Style=carStyles[0]},
new Car(){Color=carColors[1],Style=carStyles[1]},
new Car(){Color=carColors[0],Style=carStyles[2]},
new Car(){Color=carColors[2],Style=carStyles[3]},
new Car(){Color=carColors[0],Style=carStyles[4]}};
List carDupes = new List();
for (int i = 0; i < carColors.Length; i++)
{
Func dupeMatcher = c => c.Color == carColors[i];
int count = cars.Count(dupeMatcher);
if (count > 1) // we have duplicates
{
foreach (Car dupe in cars.Where(dupeMatcher).Skip(1))
{
carDupes.Add(dupe);
}
}
}
return carDupes;
}
#endregion
I'm going to come back through here later and compare this solution to all three of its inspirations, just to contrast the styles. It's rather interesting.