#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: