C# 如何计算c中嵌套字典中int值的出现次数#
我有一本字典在找C# 如何计算c中嵌套字典中int值的出现次数#,c#,dictionary,nested,C#,Dictionary,Nested,我有一本字典在找 Dictionary<string, Dictionary<string, int>> personStats 所以参数可以是(约翰,年龄,20岁),和(约翰,身高,180岁),和(约翰,性别,0)。最后,我将以带有3个附加字符串+值的条目(?)John结尾:年龄=20,身高=180,性别=0。想象一下,我运行了100次,得到了100个不同的名字和随机年龄,我想数一数有多少人的年龄是43岁。这应该可以得到42岁的用户数量: personStats.Co
Dictionary<string, Dictionary<string, int>> personStats
所以参数可以是(约翰,年龄,20岁),和(约翰,身高,180岁),和(约翰,性别,0)。最后,我将以带有3个附加字符串+值的条目(?)John结尾:年龄=20,身高=180,性别=0。想象一下,我运行了100次,得到了100个不同的名字和随机年龄,我想数一数有多少人的年龄是43岁。这应该可以得到42岁的用户数量:
personStats.Count(c => c.Value["age"] == 42);
理想情况下,您应该使用类来定义人员。差不多
enum Gender
{
Male,
Female
}
class PersonStats
{
int Age;
int Height;
Gender Gender;
}
//Add to the dictionary
var dict = Dictionary<string, PersonStats>();
dict.Add("FrankerZ", new PersonStats{
Age = 28,
Height = 180,
Gender = Gender.Male
});
//Some example filters:
dict.Count(person => person.Age == 28); //1
dict.Count(person => person.Gender == Gender.Male); //1
enum性别
{
男,,
女性
}
阶级人格状态
{
智力年龄;
内部高度;
性别;
}
//添加到字典中
var dict=Dictionary();
添加(“FrankerZ”,新人物状态{
年龄=28岁,
高度=180,
性别=性别。男性
});
//一些示例过滤器:
数字计数(人=>人年龄==28)//1.
dict.Count(person=>person.Gender==Gender.Male)//1.
您可以使用Linq来计算:
var NumberPersonsAged43 = personStats.SelectMany(p => p.Value["age"] == 43).Count();
这会使嵌套的字典变得平坦。您能给出一些示例数据的示例吗?生成一个包含一些示例值和您期望的值的示例。您好。我会试试看(我的代码很乱,因为我正在学习)。你不需要先用SelectMany将其展平,因为person属性在嵌套字典中,不能作为personStats的一部分访问吗?所以personStats KVP将由一个名称和一个person属性字典组成。谢谢!这是完美的-和ofc。成功了!我会看看你的理想版本。但我必须一步一步地走,因为我还是一个neewbie。
var NumberPersonsAged43 = personStats.SelectMany(p => p.Value["age"] == 43).Count();