我有以下代码在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。我想念什么?

最佳答案

您正在将colorItem分配给sp.TileColorItem,而不是colorList。这就是为什么如果调用colorList.IndexOf(colorItem)它将返回-1的原因。
您可能需要使用以下内容:

int index;
foreach (var item in colorList)
{
    if (item.Text == sp.TileColorItem)
    {
        index = colorList.IndexOf(item);
    }
}

08-17 04:38