Home > Mobile >  C# Sort a list based on values in another list efficiently
C# Sort a list based on values in another list efficiently

Time:02-19

Say I have a list of cars:

List<string> carList = new List<string>(){"Car1", "Car2", "Car3"};

I then have prices assigned to each car in another list where the first item corresponds to Car1 etc:

List<int> priceList = new List<int>(){50, 200, 10};

Now I want to sort my carList based on the highest price in priceList, with the expected outcome of my carList now having the order like this:

"Car2", "Car1", "Car3"

This needs to be done as fast as possible, it is the only thing that matters. It doesn't matter if carList is sorted itself or if I need to create a new list to store the sorted values in. I don't have any use of priceList after this sorting is completed and don't need its values.

CodePudding user response:

You can benefit from Linq's .Zip() to associate price with car name, then order by price, then select the car names.

List<string> sortedCars = carList
    .Zip(priceList,
        ( car, price ) => ( Name: car, Price: price))
    .OrderByDescending(car => car.Price)
    .Select(car => car.Name)
    .ToList();

Example fiddle here;

CodePudding user response:

Having the price on other List only related by the 'id' of both of them is a handicap, so I go for a intermediate List with both values, then sort it and cast it again to the original class list, a little unefficient, but you have little options to start with

List<string> cartests = carList.Select(
        (item, index) => new cartest() 
           { carName= item, carPrice = priceList[index] })
    .OrderByDescending(o=> o.carPrice )
    .Select(itemo=> itemo.carName).ToList();

Intermediate class

    private class cartest 
    { 
        public string carName{ get; set; }
        public int carPrice { get; set; }
    }

CodePudding user response:

If you can use arrays instead of lists, you can use Array.Sort(Array, Array) to sort two arrays at the same time.

Otherwise you will have to convert your lists to an array, sort the arrays, and then convert back:

List<string> carList = new List<string> { "Car1", "Car2", "Car3" };
List<int> priceList = new List<int> { 50, 200, 10 };

var carArray = carList.ToArray();

Array.Sort(priceList.ToArray(), carArray, Comparer<int>.Create((a, b) => b.CompareTo(a)));

carList = carArray.ToList();

The Comparer<int>.Create() is to reverse the sort order.

  •  Tags:  
  • c#
  • Related