如何汇总列表中的值<;t>;其中键值相同
本文关键字:gt 键值 lt 何汇总 列表 | 更新日期: 2023-09-27 18:25:33
我有一个列表,看起来像这个
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
});
我该如何评估这份名单,以便确定有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);
}
var results = from c in this_list
group c by c.key into g
select new custom(g.Key, g.Sum(x=>x.value));
//results now has two elements of the original "custom" type;
//one male with a count of 55, one female with a count 90
from c in this_list
group c.value by c.key into g
select new custom { key = g.Key, value = g.Sum() }
LINQ!
this_list.Where(c => c.key == male).Select(c => c.value).Sum();
更新:我误解了这个问题我喜欢Sam的回答:
this_list.Where(c => c.key == male).Select(c => c.value).Sum();
这些不起作用:
var maleCount = this_list.Count(item => item.key == male);
var femaleCount = this_list.Count(item => item.key == female);