我正在读取一个格式为
的文件[name, age]
所以我在循环中解析每一行,我想保存每一行的所有数据。 我的想法是使用字典列表
var testData = new List<Dictionary<string, string>>();
所以最后有类似的东西
{{Name: John; Age: 30},{Name: Doe; Age: 36}}
但我不太确定该怎么做。尝试将值添加到 testData
中:
testData[0]["Name"] = "John";
不正确。如何在 C# 中实现这种数据结构?
最佳答案
您的第一个假设很好:您需要使用 List<Dictionary<string, string>>();
.
但是,您不能简单地使用索引器分配值。您需要将项目添加到字典。
试试下面的代码:
var testData = new List<Dictionary<string, string>>();
testData.Add(new Dictionary<string, string>
{
{"Name", "John"},
{"Age", "30"} // Note: Age is a string, and will result in "Age": "30"
});
testData.Add(new Dictionary<string, string>
{
{"Name", "Doe"},
{"Age", "36"}
});
JsonConvert.SerializeObject(testData);
或者您可以使用对象初始化器:
var testData = new List<Dictionary<string, string>>
{
new Dictionary<string, string>
{
{ "Name", "John" },
{ "Age", "30" }
},
new Dictionary<string, string>
{
{ "Name", "Doe" },
{ "Age", "36" }
}
};
JsonConvert.SerializeObject(testData);
另一种选择是创建一个代表您的模型的类。对我来说,这看起来是一个更好的解决方案,如果您的文件始终代表相同的模型(人):
public class Person
{
public string Name { get; set; }
public int Age { get; set; } // Note: Age is an int, and will result in "Age": 30
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
List<Person> testData = new List<Person>();
testData.Add(new Person("John", 30));
testData.Add(new Person("Doe", 36));
JsonConvert.SerializeObject(testData);
关于c# - 类似于Json字符串的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34175090/