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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1565504/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:55:58  来源:igfitidea点击:

Most succinct way to convert ListBox.items to a generic list

c#genericscollectionstype-conversion

提问by jamiei

I am using C# and targeting the .NET Framework 3.5. I'm looking for a small, succinct and efficient piece of code to copy all of the items in a ListBoxto a List<String>(Generic List).

我正在使用 C# 并针对 .NET Framework 3.5。我正在寻找一段小而简洁且高效的代码来将ListBox中的所有项目复制到List<String>(Generic List)。

At the moment I have something similar to the below code:

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

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

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

Which works, of course, but I can't help but get the feeling that there must be a better way of doing this with some of the newer language features. I was thinking of something like the List.ConvertAllmethod but this only applies to Generic Lists and not ListBox.ObjectCollectioncollections.

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

采纳答案by AnthonyWJones

A bit of LINQ should do it:-

一点 LINQ 应该这样做:-

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

Of course you can modify the Type parameter of the Cast to whatever type you have stored in the Items property.

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

回答by DavidGouge

How about this:

这个怎么样:

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

回答by Konamiman

What about:

关于什么:

myOtherList.AddRange(lbMyListBox.Items);

EDIT based on comments and DavidGouge's answer:

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

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

回答by adrianbanks

The following will do it (using Linq):

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

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

The OfTypecall will ensure that only items in the listbox's items that are strings are used.

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

Using Cast, if any of the the items are not strings, you will get an exception.

使用Cast,如果任何项目不是字符串,您将收到异常。

回答by iruisoto

You don't need more. You get List of all values from Listbox

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

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