如何在unity内,将Dictionary存储为CSV?
时间: 2023-03-26 22:02:32 浏览: 62
可以使用CSVHelper插件来将Dictionary存储为CSV文件。首先,需要将Dictionary转换为List,然后使用CSVHelper将List写入CSV文件。具体实现可以参考以下代码:
```csharp
using System.Collections.Generic;
using System.IO;
using CsvHelper;
public static void SaveDictionaryToCSV(Dictionary<string, string> dict, string filePath)
{
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
list.Add(dict);
using (var writer = new StreamWriter(filePath))
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(list);
}
}
```
其中,dict是要保存的Dictionary,filePath是CSV文件的路径。调用SaveDictionaryToCSV方法即可将Dictionary保存为CSV文件。
相关问题
如何在unity内使用StreamWriter类将Dictionary存储为CSV?
您可以使用StreamWriter类的WriteLine方法将Dictionary中的每个键值对写入CSV文件中。具体步骤如下:
1. 创建一个StreamWriter对象,指定CSV文件的路径和文件名。
2. 遍历Dictionary中的每个键值对,将其转换为CSV格式的字符串。
3. 使用StreamWriter对象的WriteLine方法将CSV格式的字符串写入CSV文件中。
以下是示例代码:
```
using System.IO;
using System.Collections.Generic;
public void SaveDictionaryToCSV(Dictionary<string, string> dict, string filePath)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
foreach (KeyValuePair<string, string> kvp in dict)
{
string csvLine = string.Format("{},{1}", kvp.Key, kvp.Value);
writer.WriteLine(csvLine);
}
}
}
```
其中,SaveDictionaryToCSV方法接受一个Dictionary<string, string>对象和一个字符串参数,分别表示要保存的Dictionary和CSV文件的路径。在方法中,我们使用StreamWriter类将Dictionary中的每个键值对写入CSV文件中。
如何在unity内使用StreamWriter类将Dictionary<int, CSV>存储为CSV?
可以使用StreamWriter类的WriteLine方法将Dictionary<int, CSV>中的每个键值对转换为CSV格式的字符串,然后写入CSV文件中。具体实现可以参考以下代码:
```csharp
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class CSV
{
public string name;
public int age;
public float score;
public CSV(string name, int age, float score)
{
this.name = name;
this.age = age;
this.score = score;
}
public override string ToString()
{
return string.Format("{},{1},{2}", name, age, score);
}
}
public class CSVWriter : MonoBehaviour
{
private Dictionary<int, CSV> data = new Dictionary<int, CSV>();
private void Start()
{
// 添加测试数据
data.Add(1, new CSV("张三", 18, 90.5f));
data.Add(2, new CSV("李四", 20, 85.f));
data.Add(3, new CSV("王五", 22, 95.5f));
// 写入CSV文件
using (StreamWriter writer = new StreamWriter("test.csv"))
{
foreach (KeyValuePair<int, CSV> pair in data)
{
writer.WriteLine(pair.Value.ToString());
}
}
}
}
```
以上代码将Dictionary<int, CSV>中的每个CSV对象转换为CSV格式的字符串,然后写入名为"test.csv"的文件中。