开发者

Search in LinkedList<T>

开发者 https://www.devze.com 2023-01-20 13:59 出处:网络
Let\'s have this code : class student :IComparable , IComparable<student> { public string name = \"\";

Let's have this code :

class student :IComparable , IComparable<student> 
{
    public string name = "";

    public override string ToString()
    {
        return name; 
    }

    #region IComparable Members

    public int CompareTo(object obj)
    {
        if (this.name.Equals(((student)obj).name ) )
            return 0 ; 
        else
       开发者_Python百科     return -1 ; 
    }

    #endregion

    #region IComparable<student> Members

    public int CompareTo(student other)
    {
        if (this.name.Equals (other.name )) 
            return 0 ; 
        else
            return -1 ; 
    }

    #endregion
}

I am create LinkedList from this class in Main Like :

LinkedList<student> list = new LinkedList<student>(); 
list.AddLast(new student { name="Farah"}); 
list.AddLast(new student { name="Noor"}); 
list.AddLast(new student { name="Reem"});

foreach (student s in list)
{
    Console.WriteLine(s);
}

it's print : Farah Noor REEM

but when I am try to search about any element it doesn't find it , Like :

Console.WriteLine(list.Contains(new student{ name="Noor"})); 

This Print false although "student" class implements "IComparable , IComparable" !!

What should I do to work ??


The problem, that Contains doesn't works with IComparable interface. It uses Equals method. SO override it:

    public override bool Equals(object obj)
    {
        return this.CompareTo(((IComparable)obj)) == 0;
    }


Implement Equals and GetHashCode for your student class.

  • Guidelines for Implementing Equals and the Equality Operator (==)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号