I have a List that is being filled 开发者_运维百科with something like this in a loop:
myList.Add("john,smith,50,actor");
Obviously I just wrote the pure string, they are actually some variables. Now what I want to do is to export this to a text file using Stringbuilder and StringWriter which I think I can manage it (already did similar things).
So I want my textfile to look like this:
NAME SURNAME AGE WORK
john smith 50 actor
And so on. Can you help me figure out a foreach loop for this case?
const string Format = "{0,-10} {1,-10} {2,-10} {3,-10}";
var myList = new List<string>();
myList.Add("john,smithhh,50,actor");
myList.Add("a,b,c,d");
var res = myList.Select(i => i.Split(','));
Console.WriteLine(Format, "NAME", "SURNAME", "AGE", "WORK");
foreach (var line in res)
{
Console.WriteLine(Format, line[0], line[1], line[2], line[3]);
}
Output:
NAME SURNAME AGE WORK
john smithhh 50 actor
a b c d
Here is how can create a text file our or your List<string>
:
var path = @"C:\test.txt";
var streamWriter = File.Exists(path) ? File.AppendText(path) : File.CreateText(path);
using (streamWriter)
{
streamWriter.WriteLine("NAME\tSURNAME\tAGE\tWORK");
foreach (string s in myList)
{
streamWriter.WriteLine(s.Replace(",", "\t"));
}
}
since you already have separator(","), so you can directly do the following for better performance, no need to convert:
var result = new StringBuilder();
result.AppendLine("NAME\tSURNAME\tAGE\tWORK");
myList.ForEach(i => result.AppendLine(i.Replace(",", "\t")));
System.IO.File.WriteAllText("foo.txt", result.ToString());
You could split them into strings like this:
String[] strings = myList[i].Split(',');
And then get them individually like this:
for(int i = 0; i < strings.Count; i++)
{
file.Write(strings[i] + " ");
}
精彩评论