到ListBox.items转换为一个泛型列表最简洁的方式 [英] Most succinct way to convert ListBox.items to a generic list
问题描述
我使用C#和针对.NET Framework 3.5的。我在寻找一个小的,简洁,高效的一段代码复制所有项目中的列表框到列表与LT;弦乐>
(通用的List )
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 集合。
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();
当然,你可以修改演员到任何类型的已存储在项目属性的类型参数
Of course you can modify the Type parameter of the Cast to whatever type you have stored in the Items property.
这篇关于到ListBox.items转换为一个泛型列表最简洁的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!