ImmutableHashSet .Contains returns false

Rand Random

I have a list (to be precise ImmutableHashSet<ListItem> from System.Collections.Immutable) of base items and try to call the following code

_baseList.Contains(derivedItem)

but this returns false.

Even though the following code lines all return true

object.ReferenceEquals(_baseList.First(), derivedItem)
object.Equals(_baseList.First(), derivedItem)
_baseList.First().GetHashCode() == derivedItem.GetHashCode()

I can even write the following and it returns true:

_baseList.OfType<DerivedClass>().Contains(derivedItem)

What am I doing wrong, I would like to avoid writing the .OfType stuff.

Edit:

private ImmutableHashSet<BaseClass> _baseList;

public class BaseClass
{

}

public class DerivedClass : BaseClass
{

}

public void DoStuff()
{
    var items = _baseList.OfType<DerivedClass>().ToList();
    foreach (var derivedItem in items)
    {
        RemoveItem(derivedItem);
    }
}

public void RemoveItem(BaseClass derivedItem)
{
    if (_baseList.Contains(derivedItem))
    {
        //doesn't reach this place, since _baseList.Contains(derivedItem) returns false...
        _baseList = _baseList.Remove(derivedItem);
    }

    //object.ReferenceEquals(_baseList.First(), derivedItem) == true
    //object.Equals(_baseList.First(), derivedItem) == true
    //_baseList.First().GetHashCode() == derivedItem.GetHashCode() == true
    //_baseList.OfType<DerivedClass>().Contains(derivedItem) == true
}

Edit2:

Here a reproducible code of my problem, seems like ImmutableHashSet<> caches GetHashCode and doesn't compare the current GetHashCode with the entries inside the list, is there a way to tell ImmutableHashSet<> that the GetHashCode of the items could be different, atleast for the item I am currently checking since hey its the damn same reference...

namespace ConsoleApplication1
{
    class Program
    {
        private static ImmutableHashSet<BaseClass> _baseList;

        static void Main(string[] args)
        {
            _baseList = ImmutableHashSet.Create<BaseClass>();
            _baseList = _baseList.Add(new DerivedClass("B1"));
            _baseList = _baseList.Add(new DerivedClass("B2"));
            _baseList = _baseList.Add(new DerivedClass("B3"));
            _baseList = _baseList.Add(new DerivedClass("B4"));
            _baseList = _baseList.Add(new DerivedClass("B5"));

            DoStuff();
            Console.WriteLine(_baseList.Count); //output is 5 - put it should be 0...
            Console.ReadLine();
        }

        private static void DoStuff()
        {
            var items = _baseList.OfType<DerivedClass>().ToList();
            foreach (var derivedItem in items)
            {
                derivedItem.BaseString += "Change...";
                RemoveItem(derivedItem);
            }
        }

        private static void RemoveItem(BaseClass derivedItem)
        {
            if (_baseList.Contains(derivedItem))
            {
                _baseList = _baseList.Remove(derivedItem);
            }
        }
    }

    public abstract class BaseClass
    {
        private string _baseString;
        public string BaseString
        {
            get { return _baseString; }
            set { _baseString = value; }
        }

        public BaseClass(string baseString)
        {
            _baseString = baseString;
        }

        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = (_baseString != null ? _baseString.GetHashCode() : 0);
                return hashCode;
            }
        }
    }
    public class DerivedClass : BaseClass
    {
        public DerivedClass(string baseString)
            : base(baseString)
        {

        }
    }
}

If I would change the ImmutableHashSet<> to ImmutableList<> the code works fine, so if you guys don't come up with any good idea I will switch to the list.

antiduh

Objects that are used in dictionaries and other hashing-related data structures should have immutable identity - all hashing-related data structures assume that once you add the object to the dictionary, its hashcode is not going to change.

This code is not going to work:

    private static void DoStuff()
    {
        var items = _baseList.OfType<DerivedClass>().ToList();
        foreach (var derivedItem in items)
        {
            derivedItem.BaseString += "Change...";
            RemoveItem(derivedItem);
        }
    }

    private static void RemoveItem(BaseClass derivedItem)
    {
        if (_baseList.Contains(derivedItem))
        {
            _baseList = _baseList.Remove(derivedItem);
        }
    }

_baseList.Contains() in RemoveItem(), as called by DoStuff() is going to return false for every single item, because you changed the identity of the stored item - its BaseString property.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Contains always returns false

Array.contains returns false

JArray.Contains returns false

EntityManager.contains() returns false after persist()

Immutable.Set.contains returns false

strings.Contains() returns always false

ArrayList Contains with Object always returns false

Why contains() method on ArrayList always returns false?

str_contains returns true, but preg_match returns false

Element is present but `Set.contains(element)` returns false

Rect contains() returns false when clicking inside EditText

Why does Rect.contains(right,bottom) returns false?

JPA entity with collection returns false for contains method on detached member

HashSet.contains returns false when it shouldn't

Why does Contains() return false but wrapping in a list and Intersect() returns true?

HashSet.contains(object) returns false for instance modified after insertion

Check if the string contains the substring returns true when its actually false

Checking if LinearRing contains a point always returns False in Shapely

ISML isDefined() returns false altough object contains value in field

ArrayList's contains() method always returns false with custom object

empty() function returns false although array contains empty array

String contains () in Java returns false even if string is present

isNaN() returns false for anything that starts with a number, even if it contains letters

ImmutableHashSet RemoveWhere

false || false returns true

Regex: pandas.str.contains('binary: [49] ') returns False but in fact, it is True

List contains method returns false when using Math.sqrt() as a parameter

Matplotlib path.contains_points returns false for points on some edges but not others

Python's in (__contains__) operator returns a bool whose value is neither True nor False

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive