简体   繁体   English

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

[英]Convert array of strings to List<string>

I've seen examples of this done using .ToList() on array types, this seems to be available only in .Net 3.5+ . 我已经看到使用.ToList()对数组类型完成的示例,这似乎仅在.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? 我在.NET项目上使用.NET Framework 2.0,此时无法升级,所以我想知道:还有其他解决方案吗? 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)? 比循环遍历数组并将每个元素添加到此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? 如果我必须这样做,有没有办法在将它复制到我的列表后从内存中释放延迟数组?

Just use this constructor of List<T> . 只需使用List<T> 这个构造函数 It accepts any IEnumerable<T> as an argument. 它接受任何IEnumerable<T>作为参数。

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

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. PS。 There's also ToArray() method that works in other way. 还有ToArray()方法以其他方式工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM