c# - 类似于Json字符串的字典列表

标签 c# visual-studio

我正在读取一个格式为

的文件
[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/

相关文章:

c# - 保持字典的 Where() 一致

c# - 需要 Mono Zeroconf 的样本

c# - 将现有项目添加到解决方案的效果

c# - 如何在句子文本中搜索单词 [C#]

visual-studio - 是否可以更新 Web 部署项目中的 WCF 服务引用

c# - 将按下的任何键绑定(bind)到 VM WPF 中的命令

c# - ASP.NET 动态数据站点 : Force First Column to be Alphabetized

c# - DataContext.CreateDatabase() 说文件已经存在 - 但它不存在

C# - 修改 DaraGridView 中 column1 的值并将它们放入新列

visual-studio - VS 2013 中缺少 SQLite 数据提供程序