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

标签 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

最佳答案

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

如果ColorItem是你自己的类(class),你绝对可以通过覆盖 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> 作为一般的良好实践,这是一个很好的措施。不过这里并不是绝对必要的。)

关于c# - List IndexOf 返回 -1 即使有匹配的对象 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16747480/

相关文章:

C# 如何根据每个项目中的字符子集使用 lambda 表达式对字符串列表进行排序

java - 我很困惑——这段代码总是有效吗?

c++使用.indexOf在QStringList中查找以 "..."开头的文本

string - 字符串包含 'AA' 时的 IndexOf 错误

javascript - 选择排序后查找排序数组中数字位置的代码不稳定?

c# - 如何注销匿名处理程序?

c# - C#中如何删除数组中的元素

c# - 解析文本框中的单词

c# - 复制列表值

java - 如何使用 android listAdapter 识别滚动方向?