C# 如何获取ListBox中项目的索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/408320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:13:16  来源:igfitidea点击:

How Can I Get the Index of An Item in a ListBox?

c#listbox

提问by jjnguy

I am adding items to a ListBoxlike so:

我正在向这样的项目添加项目ListBox

myListBox.Items.addRange(myObjectArray);

and I also want to select some of the items I add by the following:

我还想通过以下方式选择我添加的一些项目:

foreach(MyObject m in otherListOfMyObjects) 
{
    int index = myListBox.Items.IndexOf(m);
    myListBox.SelectedIndices.Add(index);
}

however indexis always -1.

然而index总是-1

Is there a different way to get the index of an object in a ListBox?

有没有不同的方法来获取 a 中对象的索引ListBox

采纳答案by Neil Barnwell

You should make sure that MyObjectoverrides Equals(), GetHashCode()and ToString()so that the IndexOf()method can find the object properly.

你应该确保MyObject覆盖Equals()GetHashCode()并且ToString()使该IndexOf()方法能够正确地找到对象。

Technically, ToString()doesn't need to be overridden for equality testing, but it is useful for debugging.

从技术上讲,ToString()不需要为相等测试覆盖,但它对调试很有用。

回答by Kon

You can use some kind of a key for values in the listbox, like GUIDs. Then you can easily use myListBox.Items.FindByValue(value)to find the right item.

您可以对列表框中的值使用某种键,例如 GUID。然后您可以轻松地使用它myListBox.Items.FindByValue(value)来找到合适的项目。

回答by Kon

IndexOf checks the reference, so if the items in otherListOfMyObjects don't reference the same exact objects in memory as myListBox.Items, then IndexOf won't work.

IndexOf 检查引用,因此如果 otherListOfMyObjects 中的项目不引用内存中与 myListBox.Items 完全相同的对象,则 IndexOf 将不起作用。

What you could do is use linq. Here's some pseudocode that looks like C#, may compile and may actually work:

你可以做的是使用 linq。下面是一些看起来像 C# 的伪代码,可以编译并且可以实际工作:

var items =  from x in myListBox.Items where otherListOfMyObjects.Any(y => y == x /*SEE NOTE*/) select x;
foreach(item i in items)
  myListBox.SelectedItems.Add(i);

Obviously, that won't work as y==x will always return false (that's why your current method won't work). You need to substitute y==x to perform an equality comparison that will determine equality as YOU define it for MyObject. You can do this by adding an ID as Fallen suggested or by overriding a buttload of methods as Neil suggested (+s for both of them), or by just determining which properties of MyObject to check in order to identify them as exactly the same object.

显然,这不会起作用,因为 y==x 将始终返回 false(这就是您当前的方法不起作用的原因)。您需要替换 y==x 来执行相等比较,该比较将在您为 MyObject 定义时确定相等。您可以通过添加 Fallen 建议的 ID 或按照 Neil 建议的方法覆盖大量方法来实现此目的(+s 两个方法),或者仅确定要检查的 MyObject 的哪些属性以将它们识别为完全相同的对象.