vb.net 将 IList<Object> 转换为 List<String>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20425985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert IList<Object> to a List<String>
提问by Richard.Gale
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 ComboBoxcan be populated from a range of data sources.
我有一个列表(从数据库返回),我有一个组合框,我正在填充一个列表,我这样做是因为ComboBox可以从一系列数据源填充。
I need to convert the IList(Of Object)into a List(Of String).
我需要将 转换IList(Of Object)为List(Of String).
The Objecthas an override on the ToStringmethod.
在Object对超控ToString方法。
Please can anyone advise on this one?
请任何人都可以就此提出建议吗?
采纳答案by Steven Doggart
If you have a IList(Of Object), like this:
如果你有一个IList(Of Object),像这样:
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:
您可以将该列表中的项目ComboBox直接添加到 a 中,如下所示:
ComboBox1.Items.AddRange(objects.ToArray())
There is no need to first convert it to a List(Of String)since the ComboBoxautomatically calls the ToStringmethod 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:
无需先将其转换为 a,List(Of String)因为它会ComboBox自动ToString为您在列表中的每个项目上调用该方法。但是,如果您确实需要将其转换为 a List(Of String),则可以这样做:
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:
或者,如果您不想使用 LINQ 扩展方法,您可以使用老式的方法,如下所示:
Dim strings As New List(Of String)()
For Each i As Object In objects
strings.Add(i.ToString())
Next
回答by WAKU
Use linq:
使用 linq:
Private Function ConvertToListOfString(lstObject As IList(Of Object)) As List(Of String)
Return lstObject.Select(Function(e) e.ToString()).ToList()
End Function

