199

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?

3
  • 1
    Don't worry about cleaning up your arr, the garbage collector will do a lot better job of that than you will. Commented Apr 12, 2012 at 18:20
  • 41
    You specifically. And me. In fact, I think only Jon Skeet is allowed to do his own garbage collection. Commented Apr 26, 2013 at 18:59
  • @MikeChristensen Couldn't resist upvoting that for the Jon Skeet comment. lol Commented Apr 5, 2019 at 14:32

2 Answers 2

503

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

string[] arr = ...
List<string> list = new List<string>(arr);
Sign up to request clarification or add additional context in comments.

Comments

41

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.

1 Comment

@quest4truth - Visual Studio version has nothing to do with it. It will work in 2022 and VS Code as well as long as you have .NET with Linq (+ using System.Ling there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.