C#返回值索引-1 [英] C# Indexof return value -1

查看:202
本文介绍了C#返回值索引-1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从一个列表中获取一个特定项目的索引值。但是函数返回值-1。我能否知道indexof返回-1的原因是什么?

I am trying to get the index value of one particular item from one list. But the function returned value -1. May I know what's the reason of indexof return -1?

推荐答案

原因 IndexOf()返回 -1 是因为您要查找的项目在列表中不存在

The reason IndexOf() is returning -1 is because the item you are trying to find does not exist in the list.

根据文档 IndexOf 将返回如果找到,则整个列表中第一个出现的项的从零开始的索引;否则为–1。 。

According to the documentation, IndexOf will return "the zero-based index of the first occurrence of item within the entire List, if found; otherwise, –1.".

您应该逐步调试一下,您会发现尝试查找索引的项目不在您的列表中

You should step through with the debugger, you will find that the item you are trying to find the index of is not in your list.

请牢记(同样,在文档中)。 该方法使用默认的相等比较器EqualityComparer.Default为T(列表中的值的类型)确定相等性。。因此,如果您确信项目应该列在列表中,则应查看您的类型的EqualityComparer。

Keep in mind (and again, this is in the documentation). That "this method determines equality using the default equality comparer EqualityComparer.Default for T, the type of values in the list.". So if you are convinced that your item should be in the list, you should look at the EqualityComparer for your type.

这篇关于C#返回值索引-1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆