Get index of value in ObservableCollection I have an ObservableCollection&lt;MyType&gt; ItemList, and I need to know the index of a specific MyType in the collection.  However, when I hard-code the values like this:



ItemList.IndexOf(new MyType(val1, val2, val3));


it can't find the value because it is a different instance of MyType, even if all the values are the same.

So, I wrote this simple method:

private int IndexOfValInItemList(MenuItem val)
{
    for (int i = 0; i &lt; ItemList.Count; i++)
    {
        if (ItemList[i].Title == val.Title &amp;&amp; ItemList[i].Page == val.Page &amp;&amp; ItemList[i].Menu == val.Menu) { return i; }
    }

    return -1;
}


This is in the same class as the value and directly accesses the value.  I know that I could expand it to take any ObservableCollection&lt;MyType&gt;, but I haven't because ItemList cannot be passed by reference:

private ObservableCollection&lt;MenuItem&gt; _itemList = new ObservableCollection&lt;MenuItem&gt;();
public ObservableCollection&lt;MenuItem&gt; ItemList
{
    get { return _itemList; }
    set
    {
        if (_itemList == value) return;
        _itemList = value;
        OnPropertyChanged();
    }
}


Is this a good way to implement this, or is there are different way?  Is there a way I could call ItemList.IndexOf(MyType(...)) and override the equality operator used to check it?  I already tried overriding the == operator, and that did not work.

I will have a second ObservableCollection&lt;MyType&gt; soon as I finish implementing my ViewModel, so I would like to know a generic solution, but if I have to write a second method to get the value from that collection, that is OK too.
The documentation for IndexOf() clearly states how it looks for a matching value.


  This method determines equality using the default equality comparer EqualityComparer&lt;T&gt;.Default for T, the type of values in the list.


Which brings you to the documentation for EqualityComparer&lt;T&gt;.Default


  The Default property checks whether type T implements the System.IEquatable&lt;T&gt; interface and, if so, returns an EqualityComparer&lt;T&gt;that uses that implementation. Otherwise, it returns an EqualityComparer&lt;T&gt; that uses the overrides of Object.Equals and Object.GetHashCode provided by T.


You need to be overriding Equals not the == operator. Changing the behavior of the == operator to something other than Object.ReferenceEquals() for reference types should only be considered in rare cases.