【问题标题】:Most succinct way to convert ListBox.items to a generic list将 ListBox.items 转换为通用列表的最简洁方法
【发布时间】:2010-12-06 15:14:38
【问题描述】:

我正在使用 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 集合。

【问题讨论】:

标签: c# generics collections type-conversion


【解决方案1】:

你不需要更多。您从 Listbox 中获取所有值的列表

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

【讨论】:

    【解决方案2】:

    怎么样:

    myOtherList.AddRange(lbMyListBox.Items);
    

    根据 cmets 和 DavidGouge 的回答进行编辑:

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

    【讨论】:

    • 它会给出以下错误:无法从 'System.Windows.Forms.ListBox.ObjectCollection' 转换为 'System.Collections.Generic.IEnumerable'
    • ObjectCollection 是 IEnumerable 但不是 AddRange 所需的 IEnumerable
    • 这甚至不为我编译
    【解决方案3】:

    一点 LINQ 应该可以做到:-

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

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

    【讨论】:

    • List&lt;String&gt; Mylist = new List&lt;String&gt;(lbMyListBox.Items.Cast&lt;String&gt;()); 更好还是没有区别?我想,问题是,如果这样,您是否可以避免创建另一个列表。
    【解决方案4】:

    以下将执行此操作(使用 Linq):

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

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

    使用Cast,如果其中任何一项不是字符串,则会出现异常。

    【讨论】:

    • 当然,通过使用 OfType,结果列表可能会丢失项目。如果预计项目集是特定类型的,请使用 Cast,因为它不会隐藏错误类型已添加到 ListBox 的错误(这很容易做到)。 Additionaly OfType 将跳过具有转换运算符的项目到预期的输出类型,而 Cast 将调用转换器运算符。
    • 是的。我真的应该说“不能转换为字符串的项目”。 OfType 问题是一个好点,但如果 ListBox 应该只包含字符串,它会在其他东西错误地蔓延的情况下停止崩溃
    • 我希望列表框被字符串填充,但是在将非字符串对象放置在列表框中的情况下,我宁愿默默地跳过该项目而不是导致异常并处理它以几乎相同的方式例外。
    【解决方案5】:

    这个怎么样:

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

    【讨论】:

      猜你喜欢
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      相关资源
      最近更新 更多