简体   繁体   English

我如何将元组列表写入磁盘

[英]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.我有一个包含几个字段的(100 万个)元组列表,我想将它们写入磁盘,如每行 CSV 1 个元组。 Previously I was using a List<int id, string customer> and i was saving the List with the following command以前我使用的是List<int id, string customer>并且我使用以下命令保存列表

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 但我认为它花费的时间太长,还有其他方法可以保存元组列表吗?

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.您可以使用 LINQ Select 将您希望写入的任何字符串中的列表项转换为文件。它们将按顺序有效地写入。 Because Select is lazy you will not allocate another list.因为 Select 是惰性的,所以您不会分配另一个列表。

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:一般情况下,我们应该把null变成空字符串,必要时加上引号和转义"

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" 
   )));    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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