accumulating duplicates

  • Thread starter Thread starter Peter K
  • Start date Start date
P

Peter K

Hi

I have a simple class (Score) containing a "Name" property and a "Count"
property.
Instances of this class are in a list (List<Score>), and there can be
duplicate "names".

Is it possible in some simple manner, to "compact" the list - by that I
mean, to take all the duplicate names and accumulate the counts?

Eg. If I had:
Peter, 7
Peter, 3
Chris, 2
Andrew, 23
Peter, 1

Then the result would be:
Peter, 11
Chris, 2
Andrew, 23

Thanks,
Peter
 
Peter said:
Hi

I have a simple class (Score) containing a "Name" property and a "Count"
property.
Instances of this class are in a list (List<Score>), and there can be
duplicate "names".

Is it possible in some simple manner, to "compact" the list - by that I
mean, to take all the duplicate names and accumulate the counts?

Eg. If I had:
Peter, 7
Peter, 3
Chris, 2
Andrew, 23
Peter, 1

Then the result would be:
Peter, 11
Chris, 2
Andrew, 23

You can use LINQ to objects
(http://msdn.microsoft.com/en-us/library/bb397926.aspx) roughly as

List<Score> newList =
(from s in oldList
group s by s.Name into g
select new Score() {
Name = g.Key,
Count = g.Sum(s1 => s1.Count)
}).ToList();
 
Back
Top