List IndexOf返回-1,即使有匹配的对象c#

时间:2013-05-25 07:35:17

标签: c# list indexof

我有以下代码来查找ColorItem

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);

即使列表中有匹配的对象,index也始终返回-1。我错过了什么?

colorList content

colorItem content

2 个答案:

答案 0 :(得分:6)

List<T>.IndexOf在列表中查找与您传递的值相等的项目。默认情况下,对于类,相等只是对象标识 - 因此两个不同的对象被视为不相等,无论它们的字段是什么。但是,您可以通过覆盖Equals方法来更改此内容。

如果ColorItem是您自己的课程,那么您可以通过覆盖Equals(以及GetHashCode; List<T>.IndexOf未使用的Equals来完成此工作始终被覆盖以适当地与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; } } )保持一致:

IndexOf

现在IEquatable<ColorItem>应该可以正常工作。

(作为一般的良好做法,我已经实施了{{1}}作为一项良好的衡量标准。尽管如此,这并不是绝对必要的。)

答案 1 :(得分:1)

您将colorItem分配给sp.TileColorItemcolorList不在colorList.IndexOf(colorItem)。这就是为什么如果你致电-1它会返回int index; foreach (var item in colorList) { if (item.Text == sp.TileColorItem) { index = colorList.IndexOf(item); } } 。 你可能想要使用这样的东西:

{{1}}