最简单的方法是将ListBox.items转换为通用列表 [英] Most succinct way to convert ListBox.items to a generic list
问题描述
我使用C#和针对.NET Framework 3.5。我正在寻找一个小,简洁,高效的代码片段,以复制 ListBox 到列表< String>
(Generic 列表)。
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 ListBox to a 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);
}
这当然有效,但我不禁感到必须有一个更好的方法来做这个与一些较新的语言功能。我在想像 List.ConvertAll 方法,但这只是适用于通用列表,而不是 ListBox.ObjectCollection collections。
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.ConvertAll method but this only applies to Generic Lists and not ListBox.ObjectCollection collections.
推荐答案
LINQ应该这样做: -
A bit of LINQ should do it:-
var myOtherList = lbMyListBox.Items.Cast<String>().ToList();
当然,您可以将Cast的Type参数修改为存储在Items属性中的任何类型。
Of course you can modify the Type parameter of the Cast to whatever type you have stored in the Items property.
这篇关于最简单的方法是将ListBox.items转换为通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!