0

I am trying to keep track of a sorted array in c#. What I mean by this is if I have two arrays: Array 1 and Array2, and they are in a specific order so that they link together, if I sort Array 1 into ascending order and the order looks like (I am trying to keep track of the order, not the contents really):

ARRAY1   ARRAY2   sortedARRAY1
0           0          4
1           1          1
2           2          0
3           3          2
4           4          3

Is it possible to keep track of the order and arrange 'ARRAY2' in accordance to the sortedARRAY1? So it would look something like this:

ARRAY1   ARRAY2   sortedARRAY1   SortedARRAY2
0           0          4              4
1           1          1              1
2           2          0              0
3           3          2              2
4           4          3              3
5
  • I guess this is way too abstract. Can you show your arrays as code and what you've tried so far? That would also help to understand what you're trying to achieve. Commented Apr 15, 2015 at 12:02
  • So do you want to consider the values in the two arrays as paired and then sort by one component of the pair? Commented Apr 15, 2015 at 12:03
  • 1
    Why not just sort both arrays on the same conditions? Commented Apr 15, 2015 at 12:06
  • Why not write a custom sort and pass to the second array...? Commented Apr 15, 2015 at 12:06
  • With most ease, you can use dictionary of array1 as key and array2 as values. Sort the keys, you will get the same sequence of array2. This was just an idea. Hope you can write in a code. Commented Apr 15, 2015 at 12:08

1 Answer 1

4

Yes, there is an overload of Array.Sort for that (plus this and various others):

int[] array1 = new int[5];
string[] array2 = new string[array1.Length];

var rnd = new Random();

for (int i = 0; i < array1.Length; i++)
{
    array1[i] = rnd.Next();
    array2[i] = array1[i].ToString();
}

Array.Sort(array1, array2);

This will sort array1 and reorder array2 to match array1 sorting.

Sign up to request clarification or add additional context in comments.

2 Comments

If you remove the language specific part of the MSDN links (like it-it or en-us), everyone will get the page translated to their own language (or default to en-us). -- just keeping this comment here for interest. ^_^ -- answer is great, didn't know about that overload.
@Corak I've already changed to en-us. The google sadly automatically shows me the it-it versions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.