Coder Perfect

Convert a string array to a string list.


I’ve seen examples of this done with array types using.ToList(), which appears to be accessible only in.Net 3.5+. I’m using.NET Framework 2.0 on an ASP.NET project that can’t be upgraded right now, so I’m wondering if there’s another way. One that is more elegant than looping through the array and putting each element to this List (which is fine; I’m just curious if there is a better way to learn)?

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

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

foreach (string arrItem in arr)

Is there a method to deallocate the lingering array from memory after I copy it into my list if I have to do it this way?

Asked by Nick Rolando

Solution #1

Simply use the ListT> constructor. As an argument, it accepts any IEnumerableT>.

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

Answered by Dmytro Shevchenko

Solution #2

Since.Net 3.5, you can utilize the LINQ extension method, which (in some cases) improves code flow.

This is how it’s done:

using System.Linq; 

// ...

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

PS. There’s also the ToArray() method, which operates in a different way.

Answered by

Post is based on