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

jam*_*iei 58 c# generics collections type-conversion

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

目前我有类似下面的代码:

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

        foreach (String strCol in lbMyListBox.Items)
        {
            myOtherList.Add(strCol);
        }
Run Code Online (Sandbox Code Playgroud)

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

Ant*_*nes 106

一点LINQ应该这样做: -

 var myOtherList = lbMyListBox.Items.Cast<String>().ToList();
Run Code Online (Sandbox Code Playgroud)

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


adr*_*nks 27

以下将使用它(使用Linq):

List<string> list = lbMyListBox.Items.OfType<string>().ToList();
Run Code Online (Sandbox Code Playgroud)

OfType调用将确保那些使用字符串列表框中的项目,只有项目.

使用Cast,如果任何项目不是字符串,您将获得异常.

  • 是的。我真的应该说“不能转换为字符串的项目”。OfType 问题是一个很好的点,但是如果 ListBox 应该只包含字符串,它会在其他东西错误地进入的情况下停止崩溃 (2认同)

Dav*_*uge 5

这个怎么样:

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