代码之家  ›  专栏  ›  技术社区  ›  jamiei

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

  •  56
  • jamiei  · 技术社区  · 15 年前

    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 回复  |  直到 15 年前
        1
  •  112
  •   AnthonyWJones    15 年前

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

        2
  •  29
  •   adrianbanks    15 年前

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

    这个 OfType 调用将确保仅使用listbox项中的字符串项。

    使用 Cast

        3
  •  5
  •   DavidGouge    15 年前

    List<string> myOtherList = (from l in lbMyListBox.Items.Cast<ListItem>() select l.Value).ToList();
    
        4
  •  2
  •   Konamiman    15 年前

    myOtherList.AddRange(lbMyListBox.Items);
    

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

    myOtherList.AddRange(lbMyListBox.Items.Select(item => ((ListItem)item).Value));
    
        5
  •  1
  •   iruisoto    10 年前

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