[英]How can i write to disk a List of Tuples
我有一个包含几个字段的(100 万个)元组列表,我想将它们写入磁盘,如每行 CSV 1 个元组。 以前我使用的是List<int id, string customer>并且我使用以下命令保存列表
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)
您可以使用 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"
)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.