Is there a more efficient way to search for text from ListBox in a text in C#?

56 Views Asked by At

I am using Windows Forms and C#. I have a listbox that has more than 200,000 items.

I have a long string that I want to find which one of these 200,000 items appear in the string.

I wrote this code, but I wonder if there is a better way to write it:

string Codes = "";

foreach (string itm in lbxCodes.Items)
{
    if (Result.Contains(itm))
    { 
        Codes = Codes + "," + itm;
    }
}

return Codes;
1

There are 1 best solutions below

0
Fildor On BEST ANSWER

Two versions to improve the string handling:

StringBuilder

StringBuilder codes = new();

foreach (string itm in lbxCodes.Items)
{
    if (Result.Contains(itm))
    { 
        codes.Append(",").Append(itm);
    }
}

return codes.ToString();

Note that this does not fix the "leading comma" bug that you also have in the original code from the question.

List<string> + string.Join

List<string> codes = new();

foreach (string itm in lbxCodes.Items)
{
    if (Result.Contains(itm))
    { 
        codes.Add(itm);
    }
}

return string.Join(",",codes);

Note : This will not contain a leading comma!


But as already mentioned in comments: It is probably a sub-par idea to keep 200k search items in a UI-Component, in the first place. So, maybe you want to reconsider this whole approach. But then it would be a different question.