I have the following code to find the index of the ColorItem object in a List<ColorItem>
//Get the index of the color item
var colorList = dialogViewModel.Items;
var colorItem = new ColorItem();
colorItem = sp.TileColorItem;
int index = colorList.IndexOf(colorItem);
Even though there's a matching object in the list, index always returns -1. What am I missing?


List<T>.IndexOf looks for an item in the list which is equal to the value you pass it. By default, for classes, equality is simply object identity - so two different objects are treated as unequal, whatever their fields are. However, you can change this by overriding the Equals method.
If ColorItem is your own class, you can definitely make this work, by overriding Equals (and GetHashCode; which isn't used by List<T>.IndexOf, but should always be overridden to be consistent with Equals) appropriately:
public sealed class ColorItem : IEquatable<ColorItem>
{
private readonly string text;
private readonly Color color;
public string Text { get { return text; } }
public Color Color { get { return color; } }
public ColorItem(string text, Color color)
{
this.text = text;
this.color = color;
}
public override bool Equals(object other)
{
return Equals(other as ColorItem);
}
public bool Equals(ColorItem otherItem)
{
if (otherItem == null)
{
return false;
}
return otherItem.Text == text && otherItem.Color == color;
}
public override int GetHashCode()
{
int hash = 19;
hash = hash * 31 + (text == null ? 0 : text.GetHashCode());
hash = hash * 31 + color.GetHashCode();
return hash;
}
}
Now IndexOf should work fine.
(I've implemented IEquatable<ColorItem> for good measure, as general good practice. It's not strictly necessary here though.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With