【问题标题】:How can i write to disk a List of Tuples如何将元组列表写入磁盘
【发布时间】:2021-02-16 16:30:20
【问题描述】:

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

File.WriteAllLines(Configs.customers_file, customer_list);

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

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

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

foreach (var customer in customers)

【问题讨论】:

  • File.WriteAllLines(fileName, customers.Select(c =&gt; $"{c.Id},{c.customer},{c.active}"));?

标签: c# list tuples file-writing


【解决方案1】:

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

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

【讨论】:

  • 好吧,juharr 已经在 cmets 中回答了我的问题,但我将其标记为已接受的答案,谢谢!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2022-01-10
    • 2021-08-18
    • 2019-12-09
    • 2013-08-10
    • 1970-01-01
    相关资源
    最近更新 更多