lynxcs lynxcs - 8 months ago 51
C# Question

C# How to make an x and y array change based on eachother array?

I'm new to C# programming and I'm having this problem. I'll try to explain as best as I can:

let's say I have an X array that has[ 9, 2 , 4 ]
and I have an Y array containing [ 7, 5, 3 ].

I want to "link" these so when I change the X array the Y array follows it.

e.g. I sort the X array to: [ 2, 4, 9 ] and so the Y array becomes [ 5, 3, 7 ]

since in the X array 2 was "linked" to 5 in the Y array and so on.

What I want to know is if it's possible to "link" these arrays so that when I sort X, Y changes the positions of it's numbers according to how I changed X.
(And the other way around)

Sorry if worded the question wrong, I couldn't think of another way to word it.

Answer Source

I suggesting zipping both arrays into one Z:

   using System.Linq;

   // Tuple<int, int> - just a pair of two int values
   // a custom class to hold x, y values is a better design
   var Z = X
     .Zip(Y, (x, y) => new Tuple<int, int>(x, y))
     .OrderBy(item => item.Item1)  // let's sort by x
     .ThenBy(item => item.Item2)   // in case of tie by y
     .ToList();                    // or .ToArray()

whenever you want X or Y values:

   int[] Xs = Z
     .Select(item => item.Item1)
     .ToArray(); // if you want them as array

   int[] Ys = Z
     .Select(item => item.Item2)
     .ToArray(); // if you want them as array 

Edit: if you want remove an item from Z it looks as if you removing the both from X and Y:

   Z.RemoveAt(0); // let's remove the 1st item    

   Z.RemoveAll(pair => pair.Item2 < 5); // let's remove all y < 5 items

   // Let's have Y with 1st item deleted and all items < 5 removed
   int[] Ys = Z
     .Select(item => item.Item2)