简体   繁体   中英

How can i write to disk a List of Tuples

I have a list of (1 million) Tuples with a few fields and I want to write them to disk like a CSV 1 tuple per line. Previously I was using a List<int id, string customer> and i was saving the List with the following command

File.WriteAllLines(Configs.customers_file, customer_list);

Now I have converted my list to the following Tuple

List<(int id, string customer, bool status, bool active)> customers = List<(int id, string customer, bool status, bool active)>();
...populate list here
// save customers to Disk

I could use a foreach but i think its taking too long, is there any other way to save the List of tuples?

foreach (var customer in customers)

You can convert your list items in any string you wish to write to the file with LINQ Select. They will be written sequentially and efficiently. Because Select is lazy you will not allocate another list.

File.WriteAllLines(Configs.customers_file, customer_list.Select(x => CreateLine(x)));

In general case, we should let's turn null into empty string, add quotation marks and escape " when necessary:

using System.Linq;
using System.IO;

...

private static readonly char[] csvSymbols = new char[] {
  '\r', '\n', '"', ','
};

private static string Enquote(string value) {
  if (null == value)
    return "";

  return csvSymbols.Any(symbol => value.Contains(symbol))
    ? $"\"{value.Replace("\"", "\"\"")}\"";
    : value; 
} 

Then we can turn each property of the tuple into required string:

List<(int id, string customer, bool status, bool active)> customers = ...

...

File.WriteAllLines(@"c:\myFile.cs", customers
  .Select(customer => string.Join(",", 
     customer.id,
     Enquote(customer.customer),
     customer.status ? "Y" : "N", // or whatever bool representation
     customer.active ? "Y" : "N" 
   )));    

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