I have a list of objects, some of which can be null. I want it sorted by some property, with null
s at the end of list. However, List<T>.Sort()
method seems to put null
s in the beginning no matter what the comparer returns. This is a little program that I used to test this:
class Program
{
class Foo {
public int Bar;
public Foo(int bar)
{
Bar = bar;
}
}
static void Main(string[] args)
{
List<Foo> list = new List<Foo>{null, new Foo(1), new Foo(3), null, new Foo(100)};
foreach (var foo in list)
{
Console.WriteLine("Foo: {0}", foo==null?"NULL":foo.Bar.ToString());
}
Console.WriteLine("Sorting:");
list.Sort(new Comparer());
foreach (var foo in list)
{
Console.WriteLine("Foo: {0}", foo == null ? "NULL" : foo.Bar.ToString());
}
Console.ReadKey();
}
class Comparer:IComparer<Foo>
{
#region Implementation of IComparer<in Foo>
public int Compare(Foo x, Foo y)
{
int xbar = x == null ? int.MinValue : x.Bar;
int ybar = y == null ? int.MinValue : y.Bar;
return ybar - xbar;
}
#endregion
}
}
Try this yourself: sorted list is printed as
Foo: NULL
Foo: NULL
Foo: 100
Foo: 3
Foo: 1
null
s Are first, even though they're compared as int.Minvalue
. Is the method buggy or what?