How to use arrayList.contains on my object

I tried to check my ArrayList to see if the object is already exsists, but it always returns false. Is there any one that the sentence is acceptable to what I am doing wrong with ArrayList.

ArrayList arr;

void Init()
{
   arr = new ArrayList();  

}

void Fred()
{   
   CauseAssignment ca = new CauseAssignment(Param1.Text, Param2.Text);
   if(!arr.Contains(ca))
       arr.Add(ca);

}



 public class CauseAssignment
{
    private string _Path;
    public string Path
    {
        get { return _Path; }
    }

    private string _DelimRootCause;
    public string DelimRootCause
    {
        get { return _DelimRootCause; }
    }

    public CauseAssignment(string path, string delimRootCause)
    {
        _Path = path;
        _DelimRootCause = delimRootCause;
    }
    public override string ToString()
    {
        return _Path;
    }
}
+3
source share
7 answers

Contains()ArrayList methods define equalities using the implementation Equals()available to stored objects.

If you want two different instances of your class to be considered equivalent, you need to override the method Equals()to return true when they are. Then you should also overload GetHashCode()for consistency and usability in dictionaries. Here is an example:

public class CauseAssignment
{
    private string _Path;

    /* the rest of your code */

    public override bool Equals( object o )
    { 
        if( o == null || o.GetType() != typeof(CauseAssignment) )
            return false;
        CauseAssignment ca = (CauseAssignment)o;
        return ca._Path.Equals( this._Path );
    }

    public override int GetHashCode()
    {
        return _Path.GetHashCode();
    }
}
+8

Equals() GetHashCode() Contains(), , , object.Equals(), .

Equals() GetHashCode(), String.

public override bool Equals(object other) {
    CauseAssignment otherCA = other as CauseAssignment;

    if(otherCA != null) {
        return _Path.Equals(otherCA._Path) && DelimRootCause.Equals(otherCA._DelimRootCause);
    }
    return false;
}
+3

ArrayList.Contains Equals , , . "CauseAssignment"? , Equals.

+1

, , Contains() , false, arrayList , .

, equals() CauseAssignment.

+1

Equals ( GetHashcode) Contains, , . Contains Equals . CauseAssignment Equals, Object.Equals , , .

+1

.Contains() , . :

  • , :
Object o = myArrayList[i];

if(myArrayList.Contains(o)) .... // returns true
  1. .Equals(), , ArrayList , .

. http://msdn.microsoft.com/en-us/library/ms173147.aspx .

+1

arr.Contains(ca) , ca false, .

arr, , Equals.

0

Source: https://habr.com/ru/post/1721211/


All Articles