List.Contains is not working properly

I have a list containing objects, but these objects are not unique in the list. I use this code to make them unique in another list:

 foreach (CategoryProductsResult categoryProductsResult in categoryProductsResults.Where(categoryProductsResult => !resultSet.Contains(categoryProductsResult)))
 {
    resultSet.Add(categoryProductsResult);
 }

But at the end, resultSet matches theProductsResults category.

categoryProducts Repeated second line:

enter image description here

resultSet first line:

enter image description here

As you can see, the first line of resultSet and categoryProductsResult the second line is the same, but it adds the second line to resultSet.

Do you have any suggestions?

+5
source share
5 answers

Containsuses a default resolver that compares links since your class does not override Equalsand 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();
+12
source

List , EqualityComparer.Default, :

Default , T System.IEquatable(Of T) , , EqualityComparer (Of T), . EqualityComparer (Of T), Object.Equals Object.GetHashCode, T.

, IEquatable , Equals ( GetHashCode), . linq:

bool contains = list.Any(i = > i.Id == obj.Id);

+3

categoryProductsResult . -, . , ProductId - . :

foreach (CategoryProductsResult categoryProductsResult in categoryProductsResults.Where(categoryProductsResult => resultSet.ProductId !=categoryProductsResult.ProductId)
{
    resultSet.Add(categoryProductsResult);
}
+1

-. , Contains - ( GetHashCode Equals .

SO .

0

, . , , .

, Distinct , , .

0

All Articles