如何使用LinkedList <t> .Find()方法,其中T是用户定义的数据类型(对象)</t>

时间:2013-07-07 09:36:32

标签: c# linked-list

C#中的LinkedList的Find()方法适用于字符串等,但如何将它与结构,对象等一起使用?

这是我的代码:

    {
        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();
    }

它为Node2返回NULL。我在不使用独特的Hashcode等时犯了错误吗?

1 个答案:

答案 0 :(得分:2)

为了让Find返回正确的对象,您的Item类需要覆盖Equals方法。当然,您还需要覆盖GetHashCode:虽然Find的{​​{1}}没有调用LinkedList,但这两种方法需要一起更改:

  

覆盖GetHashCode的类型也必须覆盖Equals(Object);否则,哈希表可能无法正常工作。