27

Can anyone help me to create a csv file from List, my scenario is, i have a multi dimensional values like below in a List

List<string[]> lst = new List<string[]>();
lst= csv1.ToList();

lst contains the values like,

lst[0] = {string[53]}
lst[1] = {string[53]}
lst[2] = {string[53]}
lst[3] = {string[53]}
lst[4] = {string[53]}

and string[53] contains the values like

lst[0]
 string[0] = "abc"
 string[1] = "def"
 string[2] = "ghi"
 string[3] = "jkl"
 string[4] = "mno"
 ...
lst[1]
 string[0] = "123"
 string[1] = "456"
 string[2] = "789"
 string[3] = "10"
 string[4] = "11"
 ...

I just wanted to write this multi-dimensional list to csv file as each item in lst[] to rows in csv and each item in string[] to columns such that the final output in my csv is

abc,def,ghi,jkl,mno
123,456,789,10,11

Any help would be really appreciated.

AlexH
2,7101 gold badge32 silver badges37 bronze badges
asked Dec 11, 2012 at 7:36
1
  • I tried like this, String csv = String.Join(",", lst.Select(x => x.ToString()).ToArray()); but i was not getting the output. Commented Dec 11, 2012 at 7:51

2 Answers 2

36

At the simplest level, not handling quoting / escaping / multi-line CSV issues, then just loop; maybe something like:

 using (var file = File.CreateText(path))
 {
 foreach(var arr in lst)
 {
 file.WriteLine(string.Join(",", arr));
 }
 }

or a tiny bit more efficient (no intermediary string):

 using (var file = File.CreateText(path))
 {
 foreach (var arr in lst)
 {
 if (String.IsNullOrEmpty(arr)) continue;
 file.Write(arr[0]);
 for(int i = 1 ; i < arr.Length ; i++)
 {
 file.Write(',');
 file.Write(arr[i]);
 }
 file.WriteLine();
 }
 }
Kharenis
1811 gold badge2 silver badges12 bronze badges
answered Dec 11, 2012 at 7:39

1 Comment

Your second example is going to add an extra comma at the on each record
35

use linq:

File.WriteAllLines("text.txt", lst.Select(x => string.Join(",", x)));
answered Dec 11, 2012 at 7:41

2 Comments

I am trying to do this will a "|" delimiter, and keeps producing a comma separated file, any idea as to why?
@jeffkenn in the string.Join() change the "," to "|"

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.