Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting an array of strings with respect to an array of integers

am a beginner in coding and still learning, i have two arrays , first one for cars and second one for the cars speeds

string[] cars = {"Volvo", "BMW","Ford", "Mazda"};

Int[] speeds = {150,130,200,110}

So that the speed of volvo is 150 , speed of bmw is 130 speed of ford is 300 ..etc

Is there a method in c# to rearrange the arrays with respect to speed from highest to lowest speed so that the arrays become as follows

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

String[] cars = {"ford","volvo","bmw","mazda"};

Int[] speeds = {300,150,130,110};

>Solution :

A concise way to do this is to "zip" the two arrays together into one array of tuples, sort the tuples by speed, and then split the tuples back into two arrays:

var tuples = cars.Zip(speeds, (car, speed) => (car, speed))
    .OrderByDescending(tuple => tuple.speed)
    .ToList();
string[] sortedCars = tuples.Select(tuple => tuple.car).ToArray();
int[] sortedSpeeds = tuples.Select(tuple => tuple.speed).ToArray();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading