There’s a very related question: Create List<CustomObject> from List<string> however it doesn’t deal with removing duplicates at the same time.
I have the following class examples:
class Widget
{
public string OwnerName;
public int SomeValue;
}
class Owner
{
public string Name;
public string OtherData;
}
I’d like to create a list of owners based on a list of Widgets, but only unique owner names.
Here is what I tried:
List<Owner> Owners = MyWidgetList.Select(w => new Owner { Name = w.OwnerName }).Distinct().ToList();
The problem is that there are repeats in the resulting list. What am I doing wrong?
You need to define
GetHashCode()andEquals()for your object to define what equality is for your custom type. Otherwise it compares based on the reference itself.This is because the LINQ extension methods use the
IEqualityComparerinterface to compare objects. If you don’t define a custom comparer (which you can do by creating a separate class that implementsIEqualityComparer<Owner>) it will use the default equality comparer, which uses the class’sEquals()andGetHashCode()definition. Which, if you don’t override them, does reference comparisons onEquals()and returns the default object hash code.Either define a custom
IEqualityComparer<Owner>(since you’re calling distinct on a sequence of Owner) or add aEquals()andGetHashCode()for your class.Once you do that, the query you have written will work just fine.