我正在使用 C# 并以 .NET Framework 3.5 为目标。我正在寻找一小段简洁高效的代码来复制 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收藏。
最佳答案
一点 LINQ 应该可以做到:-
var myOtherList = lbMyListBox.Items.Cast<String>().ToList();
当然,您可以将 Cast 的 Type 参数修改为您在 Items 属性中存储的任何类型。
关于c# - 将 ListBox.items 转换为通用列表的最简洁方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1565504/