简体   繁体   English

foreach 某些项目在列表框中 - Winform,C#

[英]foreach Certain item is in a ListBox - Winform, C#

I would like to know how I could find the amount of times a certain item appears in a listbox我想知道如何找到某个项目出现在列表框中的次数

foreach (string Item in listBox1.Items) 
{
    Console.WriteLine("1 Item");
}
Console.ReadLine();

Unfortunately, that cycles through the entire listBox.不幸的是,这会循环整个列表框。 I only want a certain Item.我只想要一个特定的项目。

It would depend on the type of data you have bound to the ListBox and the types unique identifer (or the property you want to use for comparison).这取决于您绑定到 ListBox 的数据类型和唯一标识符类型(或您要用于比较的属性)。

For example, if you have bound a list of String to the Listbox, you could use例如,如果您已将字符串列表绑定到列表框,则可以使用

var result = listBox.Items.OfType<String>().Count(x=>x == valueToSearch);

Instead, if you have bound a Collection of Person Types to the ListBox, where Person.Id is the property you want to use for comparison, you could use相反,如果您已将 Person 类型的 Collection 绑定到 ListBox,其中 Person.Id 是您要用于比较的属性,您可以使用

var result = listBox1.Items.OfType<Person>().Count(x=>x.Id == personToSearch.Id);

You need to begin by defining what would be the property you would compare the items in the ListBox by, after which you could use Linq as shown in the examples above.您需要首先定义比较 ListBox 中项目的属性,然后您可以使用 Linq,如上面的示例所示。

Assuming that listBox1.Items: List<string> or string[] ...假设listBox1.Items: List<string> or string[] ...

Option 1: listBox1.Items.Count(item => item == "YourCertainItem");选项 1: listBox1.Items.Count(item => item == "YourCertainItem");

You could use Linq你可以使用 Linq

Option 2: listBox1.Items.Where(item => item == "YourCertainItem").Count();选项 2: listBox1.Items.Where(item => item == "YourCertainItem").Count();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM