#136 – Sorting an Array of Values Based on an Array of Keys

You can use the Array.Sort method to sort two arrays at the same time.  The values of one array are used as the keys to determine the sort order and the values of the second array are just changed to match the sequence of the first array.

Array.Sort takes two arrays.  The first is an array of keys, dictating how the elements will be sorted.  The second will just be reordered to match the sequence of the first array.

Here’s an example:

            string[] titles = { "Pride and Prejudice", "Moby-Dick", "A Tale of Two Cities",
                                "Anna Karenina", "Fahrenheit 451" };
            string[] firstWords = {
                "It is a truth universally acknowledged",
                "Call me Ishmael",
                "It was the best of times",
                "All happy families are alike",
                "It was a pleasure to burn" };

            Array.Sort(titles, firstWords);   // Sort by title

Here’s what both arrays look like after sorting:

Advertisements