如何获得List< T>中元素的索引.在C#中 [英] How to get the index of element in the List<T> in c#

查看:38
本文介绍了如何获得List< T>中元素的索引.在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中包含一些元素,例如A B CD.我想获取B的索引.我如何得到它?

I have a list who have some element like A B C D. I want to get the index of B. How i can get it?

我想用C#做到这一点.

I want to do this in C#.

推荐答案

可以很简单:

int index = list.IndexOf(b);

其中 b 是要查找的东西,但是在这里,关于相等性的定义存在歧义.默认情况下,类将使用引用相等.一个常见的错误是创建两个具有相同字段的类实例,并期望它们算作 equal .为此,您应该真正覆盖 Equals (并为相同的 T 理想地实现 IEquatable< T> ).如果覆盖 Equals ,还应该覆盖 GetHashCode 理想地 == !=运算符.

where b is the thing to find, however there is an ambiguity here over the definition of equality. By default, classes will use reference-equality. A common mistake is creating two class instances that have identical fields, and expecting them to count as equal. To do this, you should really override Equals (and ideally implement IEquatable<T> for the same T). If you override Equals, you should also override GetHashCode, and ideally the == and != operators.

另一种选择是用谓词或比较器查找匹配项,这样可以避免所有工作

Another alternative is to find the match with a predicate or comparer, which can avoid all that work

这篇关于如何获得List&lt; T&gt;中元素的索引.在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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