List IndexOf返回-1,即使有匹配的对象c#
发布时间:2020-12-16 01:54:58 所属栏目:百科 来源:网络整理
导读:我有以下代码来查找List ColorItem中的ColorItem对象的索引. //Get the index of the color itemvar colorList = dialogViewModel.Items;var colorItem = new ColorItem();colorItem = sp.TileColorItem;int index = colorList.IndexOf(colorItem); 即使列表
我有以下代码来查找List< ColorItem>中的ColorItem对象的索引.
//Get the index of the color item var colorList = dialogViewModel.Items; var colorItem = new ColorItem(); colorItem = sp.TileColorItem; int index = colorList.IndexOf(colorItem); 即使列表中有匹配的对象,索引也始终返回-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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |