Reputation: 2027
The Find() method for LinkedList in C# works fine for strings, etc, but how to use it with structs, objects, etc?
Here is my code:
{
LinkedList<Item> TestLinkedList = new LinkedList<Item>();
TestLinkedList.AddFirst(new Item(3, "Head n Shoulders"));
TestLinkedList.AddAfter(TestLinkedList.First, new Item(45, "Dell"));
//Get the 2nd node in the linklist
Item c = new Item(3, "Head n Shoulders");
LinkedListNode<Item> Node2 = TestLinkedList.Find(c);
TestLinkedList.AddAfter((Node2), new Item(32, "Adidas"));
foreach (Item i in TestLinkedList)
{
i.Print();
}
Console.ReadKey();
}
Its returning NULL for the Node2. Am I making the mistake at not using the unique Hashcode etc?
Upvotes: 1
Views: 825
Reputation: 726619
In order for the Find
to return the correct object, your Item
class needs to override the Equals
method. Of course you also need to override GetHashCode
as well: although Find
of LinkedList
does not call GetHashCode
, the two methods need to be changed together:
Types that override
Equals(Object)
must also overrideGetHashCode
; otherwise, hash tables might not work correctly.
Upvotes: 2