[英]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.