List.Contains doesn't work properly
c#, linq, list
Solution
`Contains` uses the default comparer which is comparing references since your class does not override `Equals` and `GetHashCode`.
class CategoryProductsResult
{
public string Name { get; set; }
// ...
public override bool Equals(object obj)
{
if(obj == null)return false;
CategoryProductsResult other = obj as CategoryProductsResult;
if(other == null)return false;
return other.Name == this.Name;
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}
Now you can simply use:
resultSet = categoryProductsResults.Distinct().ToList();
Problem
I have a list which contains objects but these objests aren't unique in the list. I wrte this code to make unique them in another list: ``` foreach (CategoryProductsResult categoryProductsResult in categoryProductsResults.Where(categoryProductsResult => !resultSet.Contains(categoryProductsResult))) { resultSet.Add(categoryProductsResult); } ``` But at the end resultSet is the same with categoryProductsResults. categoryProductsResult's second row : resultSet first row: As you can see resultSet's first row and categoryProductsResult's second row is the same but it adds the second row to resultSet. Do you have any suggestion?