Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most succinct way to convert ListBox.items to a generic list

I am using C# and targeting the .NET Framework 3.5. I'm looking for a small, succinct and efficient piece of code to copy all of the items in a ListBox to a List<String> (Generic List).

At the moment I have something similar to the below code:

        List<String> myOtherList =  new List<String>();         // Populate our colCriteria with the selected columns.          foreach (String strCol in lbMyListBox.Items)         {             myOtherList.Add(strCol);         } 

Which works, of course, but I can't help but get the feeling that there must be a better way of doing this with some of the newer language features. I was thinking of something like the List.ConvertAll method but this only applies to Generic Lists and not ListBox.ObjectCollection collections.

like image 855
jamiei Avatar asked Oct 14 '09 10:10

jamiei


1 Answers

A bit of LINQ should do it:-

 var myOtherList = lbMyListBox.Items.Cast<String>().ToList(); 

Of course you can modify the Type parameter of the Cast to whatever type you have stored in the Items property.

like image 198
AnthonyWJones Avatar answered Oct 06 '22 17:10

AnthonyWJones