Werewolve Werewolve - 1 month ago 5
C# Question

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 sort:

List<cTag> Week = new List<cTag>();


What I want to do is sort the List by the
date
property of the cTag class.
The date ist in the format: dd.MM.yyyy.

I read something about the
IComparable
interface, but don't know how to use it.

Answer

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); });

Edit: Above, in code, changed c2.age to c2.date

Comments