Merging duplicates in arrays in c# -


so have 2 arrays this:

array1 = {1,2,3,4}; array2 = {353, 588, 213, 353}; 

the numbers in array1 corresponds respective indexes in array2, means: 1 of 353, 2 of 588, 3 of 213, 4 of 353. want able merge duplicates in array 2 final 1 becomes:

array1 = {5,2,3}; array2 = {353,588,213}; 

i thinking looping through i'm thinking it's inefficient hoping know efficient way this.

thanks in advance!

here's example

array1 = {14,2,3,8,10,2,7,9}; array2 = {353, 588, 353, 213, 588, 213, 200, 353};  array1 = {26,12,10,7}; array2 = {353,588,213,200}; 

you can use diccionary key array2's value , dictionary's value count:

var dic = new dictionary<int, int>(); for(int = 0; < array2.length; i++) {     int index = array2[i];     if(dic.containskey(index)) {         dic[index] += array1[i];     } else {         dic.add(index, array1[i]);     } } 

then, convert dictionary arrays again need iterate on it:

array1 = new int[dic.count]; array2 = new int[dic.count];  int position = 0;  foreach (var kvp in dic) {     array1[position] = kvp.value;     array2[position] = kvp.key;     position++; } 

demo


Comments