[英]How to create a .csv file from a Dictionary<List, List<string>> in C#
我有一個字典(List,List(string))(道歉,出於某種原因,這個編輯器不允許我輸入<>),如下所示:
Key: A --> Value:{1,2,3}
Key: B --> Value:{a,b,c}
Key: C --> Value:{Hi,Hello,Hola}
我想創建一個帶有Headers的.csv文件,對應於我的字典Keys,以及對應於List的'Columns'。
因此,例如,我的csv文件中的第一列應為:列'A',值為1 2 3我的csv文件中的第二個'列'應為:列'B',值為abc等。(注意我希望保留列的順序,但如果不是這樣就可以了
或者換句話說,因為這將是逗號分隔文件,所以第一個'行'(標題)應該是: A,B,C
第2行: 1, a , Hi
第3行: 2, b, Hello
和第4行: 3, c, Hola
在C#中實現這一目標的最佳方法是什么? 我首先嘗試過研究這個,但我似乎在網上看到的大多數建議似乎都沒有使用字典(List,List(string))中的字典。
我很感激幫助。
你可以試試這個:
static void Main(string[] args)
{
//Sample data declaration
Dictionary<string, List<string>> data = new Dictionary<string, List<string>>();
data.Add("Hello", new List<string>{"1", "2", "4"});
data.Add("Foo", new List<string> { "3", "4", "7" });
data.Add("World", new List<string> { "3", "4", "7" });
DicToExcel(data, @"D:\my.csv");
}
這是邏輯:
public static void DicToExcel(Dictionary<string, List<string>> dict, string path)
{
//We will put all results here in StringBuilder and just append everything
StringBuilder sb = new StringBuilder();
//The key will be our header
String csv = String.Join(",",
dict.Select(d => d.Key));
sb.Append(csv + Environment.NewLine);
//We will take every string by element position
String csv1 = String.Join(",",
dict.Select(d => string.Join(",", d.Value.First().Take(1))));
sb.Append(csv1 + Environment.NewLine);
String csv2 = String.Join(",",
dict.Select(d => string.Join(",", d.Value.Skip(1).Take(1))));
sb.Append(csv2+ Environment.NewLine);
String csv3 = String.Join(",",
dict.Select(d => string.Join(",", d.Value.Skip(2).Take(1))));
sb.Append(csv3);
//Write the file
System.IO.File.WriteAllText(path, sb.ToString());
}
結果將是:
Hello Foo World
1 3 3
2 4 4
4 7 7
一種解決方案是將地圖轉換為列表列表。 外部列表對應於文件,內部列表對應於行。 一旦你有輸出變得容易。
在您的示例中,新數據結構將是:
[[A,B,C]
[1,a,Hi]
[2,b,Hello]
[3,c,Hola]]
地圖和數據上的一組嵌套循環將允許您進行轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.