List<T>.Sort made simple

by pietman 25. November 2009 13:14

This is a simple example of how to sort a Generic List    List(T)

using System;
using System.Collections.Generic;
public class MySortExample
{
    private static int CompareVehiclesByWeight(Vehicle x, Vehicle y)
    {
        if ((x == null) && (y == null))
             return 0;
        if ((x == null) && (y != null))
             return -1;
        if ((x != null) && (y == null))
             return 1;
        return (x.Weight.CompareTo(y.Weight));
    }
    public static void Main()
    {
        List<Vehicle> Vehicles = new List<Vehicle>();
        Console.WriteLine("\nCapacity: {0}", Vehicles.Capacity);
        Vehicles.Add(VehicleType.Car);
        Vehicles.Add(VehicleType.Bicycle);
        Vehicles.Add(VehicleType.Plane);
        Vehicles.Add(VehicleType.Ship);
        Vehicles.Add(VehicleType.Motorbike);
        Vehicles.Sort(CompareVehiclesByWeight);
    }
}

You can created multiple sorting algorithms, sorting on different elements/fields and then just call the sort method that you want to use at the appropriate time.

Tags:

c# | Generics

Add c0mment




  Country flag
biuquote
  • Comment
  • Preview
Loading


About ...

pietman celliersPietman Celliers
Bitlink  Ltd
bitlinkit.com