I see you've got the answer anyway, but...
You can avoid some ugliness by just splitting the statement into two halves:
Comparison<StatInfo> comparison = (x, y) => DateTime.Compare(x.date, y.date);
_allStatInfo.Sort(comparison);
You might want to consider just calling CompareTo
directly, too:
Comparison<StatInfo> comparison = (x, y) => x.date.CompareTo(y.date);
_allStatInfo.Sort(comparison);
You could create an IComparer<T>
implementation using my ProjectionComparer
class -
it's part of MiscUtil, and I've included an uncommented version at the bottom of
this answer. You'd then write:
_allStatInfo.Sort(ProjectionComparer<StatInfo>.Create(x => x.date));
Even if you're using .NET 2.0, you can still use LINQ by way of LINQBridge.
Here's the ProjectionComparer
class required for the second answer. The first couple of classes are really just helpers to let generic type inference work better.
public static class ProjectionComparer
{
public static ProjectionComparer<TSource, TKey> Create<TSource, TKey>
(Func<TSource, TKey> projection)
{
return new ProjectionComparer<TSource, TKey>(projection);
}
public static ProjectionComparer<TSource, TKey> Create<TSource, TKey>
(TSource ignored, Func<TSource, TKey> projection)
{
return new ProjectionComparer<TSource, TKey>(projection);
}
}
public static class ProjectionComparer<TSource>
{
public static ProjectionComparer<TSource, TKey> Create<TKey>
(Func<TSource, TKey> projection)
{
return new ProjectionComparer<TSource, TKey>(projection);
}
}
public class ProjectionComparer<TSource, TKey> : IComparer<TSource>
{
readonly Func<TSource, TKey> projection;
readonly IComparer<TKey> comparer;
public ProjectionComparer(Func<TSource, TKey> projection)
: this (projection, null)
{
}
public ProjectionComparer(Func<TSource, TKey> projection,
IComparer<TKey> comparer)
{
projection.ThrowIfNull("projection");
this.comparer = comparer ?? Comparer<TKey>.Default;
this.projection = projection;
}
public int Compare(TSource x, TSource y)
{
// Don't want to project from nullity
if (x==null && y==null)
{
return 0;
}
if (x==null)
{
return -1;
}
if (y==null)
{
return 1;
}
return comparer.Compare(projection(x), projection(y));
}
}