I have a Windows Forms application (C#) 开发者_运维知识库containing a ListBox into which I have added some items (I'm not using a DataSource). I want to filter the items in the ListBox to show only items containing a string I'm searching for.
I have done this by keeping a list of the original items and selecting matching items from that list each time the search string changes and updating the ListBox.Items
Is there a more elegant/efficient way to do this?
Is there a more elegant/efficient way?
No, not really.
You could connect through a BindingSource and that has Filter and Sort properties, but that doesn't work for a simple List<>. So you would have to use something like a DataTable and that would not be an improvement.
Your current method seems fine, especially if you can use LINQ to filter the list.
But I hope you're not looping over the Items property each time, just assign the filtered list to Listbox1.DataSource.
Here's a post that might be relevant to your question even though it is allready answered.
Filtering a listbox
精彩评论