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

问题描述

我有一个包含几个字段的(100 万)元组列表,我想将它们像 CSV 1 元组一样写入磁盘,每行。以前我使用 List 并且我使用以下命令保存列表

File.WriteallLines(Configs.customers_file,customer_list);

现在我已将列表转换为以下元组

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

我可以使用 foreach,但我认为它花费的时间太长,还有其他方法可以保存元组列表吗?

foreach (var customer in customers)

解决方法

您可以使用 LINQ Select 将列表项转换为您希望写入文件的任何字符串。它们将按顺序有效地编写。因为 Select 是惰性的,所以你不会分配另一个列表。

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

一般情况下,我们应该把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; 
} 

然后我们可以将元组的每个属性转换为所需的字符串:

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