1

I'm trying to add numbers per unique names from two list inputs as shown in the example below using C#.

Inputs
numbers: 1, 2, 3, 4, 5
names: A, B, A, B, C

The two lists that I'm trying to get as outputs are:

Outputs
uniqueNames: A, B, C
numbersPerName: 4(1+3), 6(2+4), 5

I can get the unique names from a list, but how can I add numbers per unique name after the code below?

HashSet<string> nameSet = new HashSet<string>();
for (int i = 0; i < names.Count; i++){
      nameSet.Add(names[i]);
    }
uniqueNames = nameSet;

Thank you for any help in advance!

  • 1
    These are separate lists? In oppose to, say, a list of objects with properties `name` and `number`? – Jamiec Oct 29 '20 at 20:31
  • Yes, inputs are two separate lists. I'd like to make the code dynamic, so that items in output lists grow as unique names in input lists grow. – dongyeop lee Oct 29 '20 at 20:35
  • Does this answer your question? [Getting unique items from a list](https://stackoverflow.com/questions/1388361/getting-unique-items-from-a-list) – dovid Oct 29 '20 at 20:37

1 Answers1

3

The trick here is to Zip both lists (assuming they're always the same length) and then use GroupBy and Sum

var names = new []{"A","B","A","B","C"};
var numbers = new []{1,2,3,4,5};
    
var combined = names.Zip(numbers, (name,number) => new{ Name = name, Number = number});
    
var result = combined.GroupBy(x => x.Name)
                     .Select(g => new {Name=g.Key, Value = g.Sum(x => x.Number)});
    
foreach(var item in result)
{
    Console.WriteLine($"{item.Name}: {item.Value}");
}

Live example: https://dotnetfiddle.net/6iHRR4

If you do then want back 2 separate lists you can do:

var uniqueNames = result.Select(x => x.Name);
var numbersPerName = result.Select(x => x.Value);
Jamiec
  • 133,658
  • 13
  • 134
  • 193