c# - 如何从 C# 中的 Dictionary<List, List<string>> 创建 .csv 文件

标签 c# dictionary read.csv

我有一个 Dictionary(List, List(string))(抱歉,出于某种原因,这个编辑器不允许我输入 <>) 看起来像下面这样:

Key: A --> Value:{1,2,3}
Key: B --> Value:{a,b,c}
Key: C --> Value:{Hi,Hello,Hola}

我想创建一个 .csv 文件,其中的标题对应于我的字典键,“列”对应于列表。

因此,例如,我的 csv 文件中的第一个“列”应该是: “A”列,值为 1 2 3 我的 csv 文件中的第二个“列”应该是: “B”列,值为 a b c 等。 (请注意,我希望保留列的顺序,但如果不保留也没关系)

或者换句话说,因为这将是一个逗号分隔的文件,所以第一个“行”(标题)应该是: A,B,C
第二行: 1, a, 你好 第三行: 2,b,你好 和第四行: 3,c,你好

在 C# 中实现此目的的最佳方法是什么?我曾尝试先对此进行研究,但我似乎在网上看到的大多数建议似乎都没有使用格式为 Dictionary(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

关于c# - 如何从 C# 中的 Dictionary<List, List<string>> 创建 .csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42639145/

相关文章:

c# - ASP.Net Core 集成测试

c# - Google Drive Api - 带有 Entity Framework 的自定义 IDataStore

c++ - 在 C++ 中实现 map<mpz_t, double>

python - 将字典转换为字节并再次返回python?

r - 跳过 R 中的特定行和列

c# - Unity 中的 PerThreadLifetimeManager

c# - 从 Windows 服务打印时,CreateProcessAsUser 不使用 LogonUser token

Python 字典 : Creating a prepared statement

r - 读取 csv 文件时多次跳过

r - 将多个 .csv 文件合并为一个