如何初始化包含字典列表字典? [英] How to initialize a dictionary containing lists of dictionaries?
问题描述
我开始做在C#中一点点发展,我坚持的一个问题在这里。通常我在Python开发的地方像这样的东西被很容易实现(至少对我来说),但我不知道怎么做,在C#中:
I am starting to do a little development in C#, and I am stuck with a problem here. Usually I develop in Python where stuff like this is being implemented easily (at least for me), but I have no idea how to do that in C#:
我要创建一个包含类似于下面的使用泛型集合词典列表的字典:
I want to create a dictionary containing a list of dictionaries like the following using Generic Collections:
{ "alfred", [ {"age", 20.0}. {"height_cm", 180.1} ],
"barbara", [ {"age", 18.5}, {"height_cm", 167.3} ],
"chris", [ {"age", 39.0}, {"height_cm", 179.0} ]
}
我开始与以下几点:
using System.Collections.Generic;
Dictionary<String, Dictionary<String, double>[]> persons;
但后来我想从上面一次插入三个记录到个人。我坚持语法错误的所有道路。 ?
But then I'd like to insert the three records from above at once into persons. I am stuck with syntax errors all the way.
任何人都有一个解决方案,我
Anyone have a solution for me?
编辑:
感谢你们 - 我没想到能获得如此众多的深思熟虑在这么短的时间内解答!你是伟大的!
Thank you all - I didn't expect to receive so many well thought answers in such a short time! You are great!
推荐答案
您可以使用的dictionary初始化。不一样优雅的Python的,但也有住:
You could use dictionary initializes. Not as elegant as Python, but could live with:
var persons = new Dictionary<string, Dictionary<string, double>>
{
{ "alfred", new Dictionary<string, double> { { "age", 20.0 }, { "height_cm", 180.1 } } },
{ "barbara", new Dictionary<string, double> { { "age", 18.5 }, { "height_cm", 167.3 } } },
{ "chris", new Dictionary<string, double> { { "age", 39.0 }, { "height_cm", 179.0 } } }
};
和则:
persons["alfred"]["age"];
另请注意,你需要词典<字符串,字典<字符串,双> >
此结构而不是词典<字符串,字典<字符串,双>>
另外这种结构的工作可能是一个小皮塔饼和伤害可读性和编译代码的类型安全。
Also working with such structure could be a little PITA and harm readability and compile-time type safety of the code.
在.NET是首选使用强类型对象的工作,像这样的:
In .NET it is preferred to work with strongly typed objects, like this:
public class Person
{
public double Age { get; set; }
public string Name { get; set; }
public double HeightCm { get; set; }
}
和则:
var persons = new[]
{
new Person { Name = "alfred", Age = 20.0, HeightCm = 180.1 },
new Person { Name = "barbara", Age = 18.5, HeightCm = 180.1 },
new Person { Name = "chris", Age = 39.0, HeightCm = 179.0 },
};
然后你可以使用LINQ来获取你需要的任何信息:
and then you could use LINQ to fetch whatever information you need:
double barbarasAge =
(from p in persons
where p.Name == "barbara"
select p.Age).First();
要注意的当然是使用集合不会是一样快,一个哈希表查找,但是取决于你的需要在性能,你也可以住在一起条款。
To be noted of course that using collections would not be as fast as a hashtable lookup but depending on your needs in terms of performance you could also live with that.
这篇关于如何初始化包含字典列表字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!