I am having difficulties finding a suiteble way as to search a List<> of strings i have for matches to a user specified string, I am not even sure i am going about it in the best way but what i got so far is:
// This is the input string.
string input = userDefinedStr.ToLower(); //New variable and made into lower cases.
for (int i = 0; i < listBox1.Items.Count; i++)
{
if (listBox1.Items[i].ToString().IndexOf(input, stringComparison.OrdinalIgnoreCase) >= 0)
{
listBox1.SetSelected(i, true);
}
else
{
MessageBox.Show("Sorry, There was no matches found.", "An oupps happend!");
}
}
The problem is that there can be more the one string in the List that contains the userdefined string and i guess that the best way is actually to display all the List<string> matches in the listBox1 instead of just marking the first one found.
Or can it be done in another more effective way?!?
I am new to C# and coding in general so i dont feel like i know the best way, i have read so many articles and postings but i cant find the one pointing me in the right direction on this.
You’re showing a good start, but with that
ifstatement inside thefor, you’re going to get a messagebox popping up for every item that doesn’t match.If you wish to use the code you have so far, simply add a
boolbefore thefor(initialized to false) and set it to true when you find a match. Once theforis done, test thebooland if it is still false, no match was found and so you should show your messagebox.I have suspicions that it can be done in fewer keystrokes in Linq, but it may not be quite as easy to read / understand, depending, and maintainable (/easy to read / understand) code is preferred over clever, as you will have to fix it later.