Sort a Custom Class List<T>
I would like to sort my list with the date
property.
This is my custom class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Test.Web
{
public class cTag
{
public int id { get; set; }
public int regnumber { get; set; }
public string date { get; set; }
}
}
An this is the List
that I want to sort:
List<cTag> Week = new List<cTag>();
I want to sort the List
by the date
property of the cTag
class.
The date is in the format dd.MM.yyyy
.
I read something about the IComparable
interface, but I don't know how to use it.
One way to do this is with a delegate
List<cTag> week = new List<cTag>();
// add some stuff to the list
// now sort
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.date); });
You are correct that your cTag class must implement IComparable<T>
interface. Then you can just call Sort()
on your list.
To implement IComparable<T>
interface, you must implement CompareTo(T other)
method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public string date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public DateTime date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String)
method.
For this case you can also sort using LINQ:
week = week.OrderBy(w => DateTime.Parse(w.date)).ToList();
List<cTag> week = new List<cTag>();
week.Sort((x, y) =>
DateTime.ParseExact(x.date, "dd.MM.yyyy", CultureInfo.InvariantCulture).CompareTo(
DateTime.ParseExact(y.date, "dd.MM.yyyy", CultureInfo.InvariantCulture))
);