我有一个看起来像这样的列表
List<custom> this_list = new List<custom>();
this_list.Add(new custom()
{
key = male,
value = 50
});
this_list.Add(new custom()
{
key = female,
value = 90
});
this_list.Add(new custom()
{
key = male,
value = 5
});
Run Code Online (Sandbox Code Playgroud)
我怎样才能评估这个清单,以便确定有55名男性和90名女性?另外,假设我的密钥集非常大,手动定义男性或女性或其他密钥效率低下.如何创建包含合计总计和唯一键的新列表?
感谢您的帮助和关注!
您可以GroupBy在性别上使用分组:
var query = this_list.GroupBy(x=> x.key)
.Select(g=> new {Gender = g.Key, Count = g.Sum(x=>x.value)});
foreach(var result in query)
{
Console.WriteLine("{0} : {1}", result.Gender, result.Count);
}
Run Code Online (Sandbox Code Playgroud)