Sorting in C# In C#, we can do sorting using the built-in Sort / OrderBy methods with the Comparison delegate, the IComparer , and IComparable interfaces.
The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
The List<T>
class makes this trivial for you, since it contains a Sort
method. (It uses the QuickSort algorithm, not Bubble Sort, which is typically better anyway.) Even better, it has an overload that takes a Comparison<T>
argument, which means you can pass a lambda expression and make things very simple indeed.
Try this:
CarList.Sort((x, y) => DateTime.Compare(x.CreationDate, y.CreationDate));
You could use LINQ:
listOfCars.OrderBy(x => x.CreationDate);
EDIT: With this approach, its easy to add on more sort columns:
listOfCars.OrderBy(x => x.CreationDate).ThenBy(x => x.Make).ThenBy(x => x.Whatever);
The best approach is to implement either IComparable
or IComparable<T>
, and then call List<T>.Sort()
. This will do all the hard work of sorting for you.
Another option would be to use a custom comparer:
using System;
using System.Collections.Generic;
using System.Text;
namespace Yournamespace
{
class CarNameComparer : IComparer<Car>
{
#region IComparer<Car> Members
public int Compare(Car car1, Car car2)
{
int returnValue = 1;
if (car1 != null && car2 == null)
{
returnValue = 0;
}
else if (car1 == null && car2 != null)
{
returnValue = 0;
}
else if (car1 != null && car2 != null)
{
if (car1.CreationDate.Equals(car2.CreationDate))
{
returnValue = car1.Name.CompareTo(car2.Name);
}
else
{
returnValue = car2.CreationDate.CompareTo(car1.CreationDate);
}
}
return returnValue;
}
#endregion
}
}
which you call like this:
yourCarlist.Sort(new CarNameComparer());
Note: I didn't compile this code so you might have to remove typo's
Edit: modified it so the comparer compares on creationdate as requested in question.
I would just use the build in List.Sort method. It uses the QuickSort algorithm which on average runs in O(n log n).
This code should work for you, I change your properties to auto-properties, and defined a static CompareCarSpecs method that just uses the already existing DateTime.CompareTo method.
class Program
{
static void Main(string[] args)
{
List<CarSpecs> cars = new List<CarSpecs>();
cars.Sort(CarSpecs.CompareCarSpecs);
}
}
public class CarSpecs
{
public string CarName { get; set; }
public string CarMaker { get; set; }
public DateTime CreationDate { get; set; }
public static int CompareCarSpecs(CarSpecs x, CarSpecs y)
{
return x.CreationDate.CompareTo(y.CreationDate);
}
}
Hope this helps.
Putting some of the pieces mentioned here together. This compiles and works in C# 4.x and VS2010. I tested with a WinForm
. So add the method to the WinForm
Main()
. You will need the System.Linq
and System.Generic.Collection
s assemblies at least.
private void SortCars()
{
List<CarSpecs> cars = new List<CarSpecs>();
List<CarSpecs> carsSorted = new List<CarSpecs>();
cars.Add(new CarSpecs
{
CarName = "Y50",
CarMaker = "Ford",
CreationDate = new DateTime(2011, 4, 1),
});
cars.Add(new CarSpecs
{
CarName = "X25",
CarMaker = "Volvo",
CreationDate = new DateTime(2012, 3, 1),
});
cars.Add(new CarSpecs
{
CarName = "Z75",
CarMaker = "Datsun",
CreationDate = new DateTime(2010, 5, 1),
});
//More Comprehensive if needed
//cars.OrderBy(x => x.CreationDate).ThenBy(x => x.CarMaker).ThenBy(x => x.CarName);
carsSorted.AddRange(cars.OrderBy(x => x.CreationDate));
foreach (CarSpecs caritm in carsSorted)
{
MessageBox.Show("Name: " +caritm.CarName
+ "\r\nMaker: " +caritm.CarMaker
+ "\r\nCreationDate: " +caritm.CreationDate);
}
}
}
public class CarSpecs
{
public string CarName { get; set; }
public string CarMaker { get; set; }
public DateTime CreationDate { get; set; }
}
If you're after an efficient way of sorting, I'd advise against using bubble sort and go for a quick sort instead. This page provides a rather good explanation of the algorithm:
http://www.devhood.com/Tutorials/tutorial_details.aspx?tutorial_id=574
Best of luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With