c# - Convert array of strings to List<string>

ID : 20218

viewed : 9

Tags : c#c#-2.0c#

Top 5 Answer for c# - Convert array of strings to List<string>

vote vote

93

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

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

81

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.

vote vote

77

vote vote

69

Sometimes using libraries are cool when you do not want to reinvent the wheel, but in this case one can do the same job with fewer lines of code and easier to read compared to using libraries. Here is a different approach which I find very easy to use.

  1. In this example, I use StreamReader to read the file
  2. Regex to detect the delimiter from each line(s).
  3. An array to collect the columns from index 0 to n

using (StreamReader reader = new StreamReader(fileName))     {         string line;           while ((line = reader.ReadLine()) != null)         {             //Define pattern             Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");              //Separating columns to array             string[] X = CSVParser.Split(line);              /* Do something with X */         }     } 
vote vote

52

CSV can get complicated real fast.

Use something robust and well-tested:
FileHelpers: www.filehelpers.net

The FileHelpers are a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.

Top 3 video Explaining c# - Convert array of strings to List<string>

Related QUESTION?