如何在List <t>中使用键值相同的总值</t>

时间:2012-02-21 21:59:54

标签: c#

我有一个看起来像这样的列表

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名女性?另外,假设我的密钥集非常大,手动定义男性或女性或其他密钥效率低下。如何创建包含合计总计和唯一键的新列表?

感谢您的帮助和关注!

5 个答案:

答案 0 :(得分:9)

您可以在性别上使用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);
}

答案 1 :(得分:4)

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

答案 2 :(得分:2)

from c in this_list
group c.value by c.key into g
select new custom { key = g.Key, value = g.Sum() }

答案 3 :(得分:2)

LINQ!

this_list.Where(c => c.key == male).Select(c => c.value).Sum();

答案 4 :(得分:-1)

更新:我误解了这个问题。我喜欢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);