1

I have a List with a Tuple that contains two strings and an int:

List<Tuple<string, string, int>> peopleList = new List<Tuple<string, string, int>>();

This Tuple is populated from a lookup to a database and using a DataReader with a list of names, numbers and an int.

I want to remove duplicates from the list and count up the ints.

I've looked at this List Distinct entries based on property and sum of duplicates - which is most similar to what I want but I'm using tuples and struggling to understand how to remove the duplicates and add the numbers properly.

var group = peopleList.GroupBy(x => x)
.Select(x => new { Name = x.Key.Item1, No = x.Key.Item2, Sum = x.Sum(g => g.Item3) });

I expect to get back a list that has all the people and their corresponding counted sums.

So:

James, 12, 5
Jerry, 15, 2
James, 12, 10
Helen, 87, 8
Jerry, 15, 8

Becomes:

James, 12, 15
Jerry, 15, 10
Helen, 87, 8
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
J. James
  • 59
  • 8

1 Answers1

5

Well, you want to GroupBy by Name and No only (we want to collect, say, all James, 12 into one chunk), not by entire Tuple:

var group = peopleList
  .GroupBy(x => new {
     Name = x.Item1,
     No   = x.Item2
   })
  .Select(chunk => new {
     Name = chunk.Key.Name,
     No   = chunk.Key.No,
     Sum  = chunk.Sum(item => item.Item3) 
   })
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215