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.
4ff30b66-3faa-4e10-a4c4-ae93139c69c5|0|.0
Tags:
c# | Generics