你可以使用字典初始化。虽然不如Python优雅,但是可以胜任:
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"];
此外还要注意,您需要使用
Dictionary<string,Dictionary<string,double>>
而不是
Dictionary<string,Dictionary<string,double> []>
来构建此结构。
使用这样的结构可能会有点麻烦,并且会影响代码的可读性和编译时类型安全性。
在.NET中,最好使用强类型对象,如下所示:
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来获取所需的任何信息:
double barbarasAge =
(from p in persons
where p.Name == "barbara"
select p.Age).First();
当然需要注意的是,使用集合比哈希表查找速度更慢,但根据你在性能方面的需求,你可能可以接受这一点。