C# 将项目集合从列表框转换为通用列表

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

Casting an Item Collection from a listbox to a generic list

c#listcastinglistbox

提问by Alex

I want to find a better way of populating a generic list from a checkedlistbox in c#.

我想找到一种更好的方法来从 c# 中的选中列表框填充通用列表。

I can do the following easily enough:

我可以很容易地做到以下几点:

List<string> selectedFields = new List<string>();

foreach (object a in chkDFMFieldList.CheckedItems) {
         selectedFields.Add(a.ToString());
         } 

There must be a more elagent method to cast the CheckedItems collection to my list.

必须有一个更灵活的方法来将 CheckedItems 集合转换到我的列表中。

采纳答案by Matt Hamilton

Try this (using System.Linq):

试试这个(使用 System.Linq):

OfType()is an extension method, so you need to use System.Linq

OfType()是一个扩展方法,所以你需要使用 System.Linq

List<string> selectedFields = new List<string>();
selectedFields.AddRange(chkDFMFieldList.CheckedItems.OfType<string>());

Or just do it in one line:

或者只在一行中完成:

List<string> selectedFields = chkDFMFieldList.CheckedItems.OfType<string>().ToList();

回答by Ken Browning

If you don't have access to LINQ then there isn't a more elegant way since you're performing a second operation on the list items (calling ToString()) in addition to populating the selectedFields collection.

如果您无权访问 LINQ,那么没有更优雅的方法,因为ToString()除了填充 selectedFields 集合之外,您还要对列表项执行第二个操作(调用)。

回答by nawfal

This is not exactly the answer to your requirement, but posting a more general answer. You could do it in a variety of ways:

这不完全是您要求的答案,而是发布了更一般的答案。您可以通过多种方式做到这一点:

1)

1)

T[] items = new T[lb.Items.Count];
lb.Items.CopyTo(items, 0);
var lst = new List<T>(items);

2) looping and adding using foreachas you mentioned.

2)循环和添加使用,foreach如你所提到的。

3) using Linq

3)使用Linq

var lst = lb.Items.Cast<T>().ToList();

4) or

4) 或

var lst = lb.Items.OfType<T>().ToList();

When I did some performance testing like below, I found copying to array method the fastest while the Linq methods slower. Of course in real world scenarios these wouldnt matter. I prefer the 3rd method (Linq) for readability.

当我进行如下的一些性能测试时,我发现复制到数组方法的速度最快,而 Linq 方法的速度较慢。当然,在现实世界中,这些都无关紧要。我更喜欢第 3 种方法 (Linq) 以提高可读性。

DateTime d = DateTime.Now;
for (int i = 0; i < 10000; i++)
{
    Action();
}
MessageBox.Show((DateTime.Now - d).TotalMilliseconds.ToString());

For an iteration of 10000 times run multiple times with about 300 items in list box,

对于 10000 次迭代,在列表框中多次运行大约 300 个项目,

1) ~100ms

1) ~100ms

2) ~150ms

2) ~150ms

3) ~250ms

3) ~250ms

4) ~260ms

4) ~260ms