If this is something you might need to do in more than one place then you should define a class that implements the IComparer interface and compares two instances of your type by that property. There are generic and standard versions of the IComparer interface but it should be enough to just implement the generic version.
C# Code:
public class SomeType
{
private DateTime _date;
public DateTime Date
{
get
{
return _date;
}
set
{
_date = value;
}
}
}
C# Code:
public class SomeTypeComparer : IComparer<SomeType>
{
public int Compare(SomeType x, SomeType y)
{
return DateTime.Compare(x.Date, y.Date);
}
}
Now you can sort a List or array of your instances of your type by passing an instance of your IComparer to the Sort method:
C# Code:
List<SomeType> list = new List<SomeType>();
// Add items here.
// Sort by Date property.
list.Sort(new SomeTypeComparer());
If you only need to do it in one place then you should use a Comparison delegate instead. In that case you declare a method that has the same signature as the Comparison delegate:
C# Code:
private int CompareSomeTypes(SomeType x, SomeType y)
{
return DateTime.Compare(x.Date, y.Date);
}
Note that it is basically the same as the Compare method of the IComparer. To sort your array or list you now create a Comparison delegate for that method:
C# Code:
List<SomeType> list = new List<SomeType>();
// Add items here.
// Sort by Date property.
list.Sort(new Comparison<SomeType>(CompareSomeTypes));