-2

I'm trying to sort a list of cars by their price range. Currently I'm unsure if I've even sorted it correctly with IComparable, and I can't figure out how I print the list after it's sorted, I can only print them in the order they were declared.

using System;
using System.Collections.Generic;

namespace Interface1
{
    class Program
    {
        class Car : IComparable<Car>
        {
            public string Make { get; set; }
            public string Model { get; set; }
            public double Price { get; set; }

            public int CompareTo(Car car)
            {
                return this.Price.CompareTo(car.Price);
            }

            static void Main(string[] args)
            {
                List<Car> cars = new List<Car>()
            {
                new Car(){Make = "Skoda", Model = "Fabia", Price = 50000},
                new Car(){Make = "Skoda", Model = "Octavia", Price = 60000},
                new Car(){Make = "Nissan", Model = "Juke", Price = 45000 }
            };

                foreach (var car in cars)
                    Console.WriteLine(car.Price);

            }
        }
    }
}

Have I done the sorting correctly? How can I print it properly?

omic96
  • 117
  • 1
  • 1
  • 4
  • 1
    And where you sorted the list? – Selvin Sep 25 '20 at 14:26
  • Does this answer your question? [How do I use the IComparable interface?](https://stackoverflow.com/questions/435404/how-do-i-use-the-icomparable-interface) – Wai Ha Lee Sep 25 '20 at 14:27
  • You may want to look into the [SortedList class](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2?view=netframework-4.8). What you've used is just a plain list that doesn't do any sort automatically, even though you've correctly implemented `IComparable`. – Alejandro Sep 25 '20 at 14:29

1 Answers1

1

Change this line as so

foreach (var car in cars.OrderBy(x => x.Price))
                Console.WriteLine(car.Price);

You can add a different comparer as well in the OrderBy function.

Y Stroli
  • 339
  • 3
  • 8