Convert array of strings to List<string>

喜你入骨 提交于 2019-11-26 10:22:32

问题


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)?

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?


回答1:


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

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



回答2:


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

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.



来源:https://stackoverflow.com/questions/10129419/convert-array-of-strings-to-liststring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!