简体   繁体   中英

How to total values in a List<t> where key values are the same

I have a List that looks like this

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
});

How would I be able to evaluate this list so I can determine that there are 55 males and 90 females? Also, let's suppose that my keyset is very large and it would be inefficient to manually define male or female or another key. How would I create a new list containing the combined totals and unique keys?

Thanks for any help and attention!

You could use a grouping using GroupBy on the gender:

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();

Update: I misread the question. I like Sam I am's answer:

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

These won't work:

var maleCount = this_list.Count(item => item.key == male);
var femaleCount = this_list.Count(item => item.key == female);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM