Convert IList<Object> to a List<String>

8k views Asked by At

I have a list (returned from database) and I have a combo box which I am populating with a list, I am doing this because the ComboBox can be populated from a range of data sources.

I need to convert the IList(Of Object) into a List(Of String).

The Object has an override on the ToString method.

Please can anyone advise on this one?

2

There are 2 answers

2
Steven Doggart On BEST ANSWER

If you have a IList(Of Object), like this:

Dim objects As IList(Of Object) = New List(Of Object)({"test", "test2"})

You can add the items in that list to a ComboBox, directly, like this:

ComboBox1.Items.AddRange(objects.ToArray())

There is no need to first convert it to a List(Of String) since the ComboBox automatically calls the ToString method for you on each item in the list. However, if you really need to convert it to a List(Of String), you can do it like this:

Dim strings As List(Of String) = objects.Select(Function(x) x.ToString()).ToList()

Or, if you don't want to use the LINQ extension methods, you could do it the old-fashioned way, like this:

Dim strings As New List(Of String)()
For Each i As Object In objects
    strings.Add(i.ToString())
Next
0
WAKU On

Use linq:

    Private Function ConvertToListOfString(lstObject As IList(Of Object)) As List(Of String)
        Return lstObject.Select(Function(e) e.ToString()).ToList()
    End Function