简体   繁体   中英

C# Dictionary to .csv

I have C# Dictionary and I want create a .csv file from it. For example I have this dictionary:

Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("0", "0.15646E3");
data.Add("1", "0.45655E2");
data.Add("2", "0.46466E1");
data.Add("3", "0.45615E0");

And I wanna this .csv file output:

0;0.15646E3;
1;0.45655E2;
2;0.46466E1;
3;0.45615E0;

How can I do this?

Maybe the easiest:

String csv = String.Join(
    Environment.NewLine,
    data.Select(d => $"{d.Key};{d.Value};")
);
System.IO.File.WriteAllText(pathToCsv, csv);

You'll need to add using LINQ and use at least .NET 3.5

Try the following

using (var writer = new StreamWriter(@"the\path\to\my.csv")) {
  foreach (var pair in data) {
    writer.WriteLine("{0};{1};", pair.Key, pair.Value);
  }
}

Note: This will fail to work if the key or value elements can contain a ; . If so you will need to add an escaping mechanism to handle that

  File.WriteAllLines(@"pathtocsv.csv", data.Select(x => x.Key + ";" + x.Value + ";")));

My dictionary was similar to the one in the question posed above (by user1387150) except the VALUE part was an array (of doubles, iedouble[]).

Adjusting Jared's solution above, allows a Dictionary<string, double[]> to be written to csv as follows:

    using (var writer = new StreamWriter(@"C:\path\test.csv"))
    {
        foreach (var pair in data)
        {
            writer.WriteLine("{0},{1};", pair.Key, String.Join(",", pair.Value.Select(x => x.ToString()).ToArray()));
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM