Search code examples
c#listvisual-studio-2008sorting.net-2.0

Sorting out list with several properties


I am pretty confused with sorting out list in C#, I have gone through different tutorials for sorting e.g. sorting using list (sort method) or use IComparable but nothing actually helped me with what I want.

for example I have a list of cars,

Car Number

Car Title

and few other properties

Now Car number can be any double number or it can be Nan (null) and Car Title can never be null.

I want to sort list in a way that first it gets sorted by Car Numbers and if they are not available for a car then use its title to sort rest of cars.

so if I have something like this,

Car 1      100.0 (car number)                  BMW x6 (car name)
Car 2      (there isn't any car number)        Mercedies A class (car name)
Car 3      99.0                                Alpha Romeo
Car 4      1.2                                 Jeep
Car 5      4.1                                 Victoria Marshall 1933
Car 6      no number                           Vauxhal

Out put I want my list class to be sorted as

Car 4, Car 5, Car 3, Car 1, Car 2, Car 6

Thanks for help.


Solution

  • try something like

    var lst = new List<Cars>()
    
    //add cars to list
    
    lst = lst.Orderby(c => c.CarNumber).ToList();
    

    you can extend it like this:

    lst = lst.Orderby(c => c.CarNumber).ThenBy(c=> c.Title).ToList();
    

    Or

    You implement the IComparable so it will sort the way you want:

    public class Car : IComparable<Car> 
    { 
        public string Number { get; set; } 
    
        public int CompareTo(Car obj) 
        { 
            return obj.Number.CompareTo(Number); 
        } 
    }