I have a list of items (lets says 30 strings); I'm trying to figure out how to write to a txt file 5 items, then new line, next 5 items, etc. Like this:
List<string> blah;
//List contains:
1
2
3
4
5
6
7
8
9
10
I want to write to a txt file so it looks like this:
1 2 3 4 5
6 7 8 9 10
I can't seem to figure out a counter that will write this. I'm using StreamWriter if that matters.
EDIT: This is what I have currently but only writes blank lines.
for (var a = 0; a < ls.Count; a++)
{
foreach (string s in ls)
{
if (a == 0)
{
sr.Write(s);
}
else if((a % 5) == 0)
{
sr.Write(s);
sr.Write("\t");
}
}
}
This is driving me nuts because I know it a simple counter I need to basically say "after you write 5 items, start new line."
In pseudo code
for (int i = 0; i < list.Count; i++) {
if (i == 0) {
append to empty file (value)
} else if ((i % 5) == 0) {
append to new line (CR LF + value)
} else {
append to current line ("spaces or tab" + value)
}
}
StringBuilder sb = new StringBulder();
for (int i = 0; i < blah.Count; i++)
{
sb.Append(blah[i].ToString());
if (i % 5 == 0)
{
sb.AppendLine();
}
else
{
sb.Append(" ");
}
}
Expanding on JohnP's comment:
for(var i = 0; i < blah.Count; i++)
{
if(i % 5 == 0)
//do new line
YourPrintFunction(i);
}
With LINQ:
StringBuilder sb = new StringBuilder();
int i = 0;
blah.ForEach(s => { if ((++i % 5) == 0) sb.AppendLine(s); else sb.Append(s + "\t"); });
File.WriteAllText("filename", sb.ToString());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.