Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c# - 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+. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...