C# 将字符串数组转换为 List<string>

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

Convert array of strings to List<string>

c#c#-2.0

提问by Nick Rolando

I've seen examples of this done using .ToList()on array types, this seems to be available only in .Net 3.5+. I'm working with .NET Framework 2.0 on an ASP.NET project that can't be upgraded at this time, so I was wondering: is there another solution? One that is more elegant than looping through the array and adding each element to this List (which is no problem; I'm just wondering if there is a better solution for learning purposes)?

我已经看到使用.ToList()数组类型完成此操作的示例,这似乎仅在 .Net 3.5+ 中可用。我在一个目前无法升级的 ASP.NET 项目上使用 .NET Framework 2.0,所以我想知道:还有其他解决方案吗?一种比循环遍历数组并将每个元素添加到此 List 更优雅的方法(这没问题;我只是想知道是否有更好的解决方案用于学习目的)?

string[] arr = { "Alpha", "Beta", "Gamma" };

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

foreach (string arrItem in arr)
{
    openItems.Add(arrItem);
}

If I have to do it this way, is there a way to deallocate the lingering array from memory after I copy it into my list?

如果我必须这样做,有没有办法在我将它复制到我的列表后从内存中释放它?

采纳答案by Dmytro Shevchenko

Just use this constructorof List<T>. It accepts any IEnumerable<T>as an argument.

只要使用此构造List<T>。它接受 anyIEnumerable<T>作为参数。

string[] arr = ...
List<string> list = new List<string>(arr);

回答by andrew.fox

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

从 .Net 3.5 开始,您可以使用 LINQ 扩展方法(有时)使代码流更好一点。

Usage looks like this:

用法如下所示:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray()method that works in other way.

附注。还有ToArray()一种方法可以以其他方式工作。