简体   繁体   中英

auto-increment value on Append CSV function in C#

I have a function to add some text in csv file , i add one line in the loop.

Actually i have a 'int' value who i increment in a loop .

But i want to know if is possible to use an auto-increment value like in sql ?

Like this : csv.AppendLine(/*auto-increment*/+";SomeText");


My code:

I create my value with this:

 private StringBuilder csv ; private int test; 

i initialize it before my loop:

 csv = new StringBuilder(); 

i add my value in my loop

 csv.AppendLine((value++)+";SomeText"); 

and i save it at the end off my loop

 File.WriteAllText("Myfile.csv", csv.ToString()); 

Thanks

One option is, instead of using StringBuilder use List<string> and add the content.

Magic happens when you writing to the file. Use overloaded selector to pass index, and use this index and format the string.

File.WriteAllLines("Myfile.csv", list.Select((x,i) => string.Format("{0};{1}", i,x)));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM