Search code examples
c#winformslistbox-control

How to search listbox items with only part of its text


I have a C# WinForms application. There is a listbox filled with values in this format:

category:user:id
Food:tester:17

etc.

Now, I need to get if an item is included in this Listbox, knowing only the category and ID, I don't know the user. So technically, I need to do something like this (pseudocode):

if(MyListBox.Items.Contains("Food:*:17"))

where the * would mean "anything". Is there a way of doing this?


Solution

  • Assuming the listbox is filled directly with strings, the easiest way would be a combination of linq and regex:

     if(MyListBox.Items.Cast<string>().Any(s => Regex.IsMatch(s, "Food:.*:17")))  //(For RegEx: using System.Text.RegularExpressions )
    

    or more strict, if the items are always a combination of value:value:value and you only check the first and third value:

    if (MyListBox.Items.Cast<string>().Any(s => { var values = s.Split(':'); return values[0] == "Food" && values[2] == "17"; }))