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

C#GenericsCollectionsType Conversion

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

The following will do it (using Linq):

List<string> list = lbMyListBox.Items.OfType<string>().ToList();

The OfType call will ensure that only items in the listbox's items that are strings are used.

Using Cast, if any of the the items are not strings, you will get an exception.

Solution 3 - C#

How about this:

List<string> myOtherList = (from l in lbMyListBox.Items.Cast<ListItem>() select l.Value).ToList();

Solution 4 - C#

What about:

myOtherList.AddRange(lbMyListBox.Items);

EDIT based on comments and DavidGouge's answer:

myOtherList.AddRange(lbMyListBox.Items.Select(item => ((ListItem)item).Value));

Solution 5 - C#

You don't need more. You get List of all values from Listbox

private static List<string> GetAllElements(ListBox chkList)
        {
            return chkList.Items.Cast<ListItem>().Select(x => x.Value).ToList<string>();
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjamieiView Question on Stackoverflow
Solution 1 - C#AnthonyWJonesView Answer on Stackoverflow
Solution 2 - C#adrianbanksView Answer on Stackoverflow
Solution 3 - C#DavidGougeView Answer on Stackoverflow
Solution 4 - C#KonamimanView Answer on Stackoverflow
Solution 5 - C#iruisotoView Answer on Stackoverflow