HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Get index of value in ObservableCollection

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
indexgetobservablecollectionvalue

Problem

I have an ObservableCollection 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

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, but I haven't because ItemList cannot be passed by reference:

private ObservableCollection _itemList = new ObservableCollection();
public ObservableCollection 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` 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.

Solution

The documentation for IndexOf() clearly states how it looks for a matching value.


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

Which brings you to the documentation for EqualityComparer.Default


The Default property checks whether type T implements the System.IEquatable interface and, if so, returns an EqualityComparerthat uses that implementation. Otherwise, it returns an EqualityComparer 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.

Context

StackExchange Code Review Q#75675, answer score: 6

Revisions (0)

No revisions yet.