最简洁的方法将ListBox.items转换为通用列表

时间:2009-10-14 10:35:50

标签: c# generics collections type-conversion

我正在使用C#并以.NET Framework 3.5为目标。我正在寻找一个小巧,简洁且高效的代码,将ListBox中的所有项目复制到List<String>(通用List)。

目前我的代码类似于以下代码:

        List<String> myOtherList =  new List<String>();
        // Populate our colCriteria with the selected columns.

        foreach (String strCol in lbMyListBox.Items)
        {
            myOtherList.Add(strCol);
        }

当然,这是有效的,但我不禁感到必须有更好的方法来使用一些较新的语言功能。我在想类似于List.ConvertAll方法的内容,但这仅适用于通用列表,而不适用于ListBox.ObjectCollection集合。

5 个答案:

答案 0 :(得分:104)

一点LINQ应该这样做: -

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

当然,您可以将Cast的Type参数修改为Items属性中存储的任何类型。

答案 1 :(得分:27)

以下内容(使用Linq):

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

OfType调用将确保仅使用列表框项目中的字符串项。

使用Cast,如果任何项目不是字符串,您将获得例外。

答案 2 :(得分:5)

这个怎么样:

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

答案 3 :(得分:2)

怎么样:

myOtherList.AddRange(lbMyListBox.Items);

编辑基于评论和DavidGouge的回答:

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

答案 4 :(得分:1)

你不需要更多。您将获得列表框

中所有值的列表
private static List<string> GetAllElements(ListBox chkList)
        {
            return chkList.Items.Cast<ListItem>().Select(x => x.Value).ToList<string>();
        }