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).
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
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.
Assuming that listBox1.Items: List<string> or string[]
...
Option 1: listBox1.Items.Count(item => item == "YourCertainItem");
You could use Linq
Option 2: listBox1.Items.Where(item => item == "YourCertainItem").Count();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.