views:

2000

answers:

4

I have a generic list of objects in C#, for example sake, here's what the object might be.

public class Thing {
    public string Name { get; set; }
    public DateTime EditDate { get; set; }
}

var things = new List<Thing>();

Now I want to call:

thing.Sort((t1, t2) => t1.EditDate.CompareTo(t2.EditDate));

However, some of my EditDate properties are null. I want these objects with a null EditDate property to show up at the top of my list (i.e. closer to the zero index). How can I do this?

A: 

List has a sort function that takes a delegate.

Now that I've read the question

TheList.Sort(int delegate(Type a, Type b)
{
    if (a.memeber == null) return -1;
    if (b.memeber == null) return 1;
    if (a.memeber<b.memeber) return -1;
    if (b.memeber<a.memeber) return 1;
    return 0;
}
BCS
+13  A: 

You can create a somewhat more complex lambda, such as:

things.Sort((t1, t2) => 
{
 if (t1 == null)
 {
   return (t2 == null) ? 0 : -1;
 }
 if (t2 == null)
 {
   return 1;
 }
 return t1.EditDate.CompareTo(t2.EditDate);
});

EndDate cannot be null as it is a value type. However, if you had a specific value of EndDate that you consider as null, you could modify the above code to take that into account in a similar fashion to how I've coped with t1 or t2 being null.

Jeff Yates
You should switch == to Object.Reference equals. You're looking for object identity but asking for object equality. These are sadly two different items with only one construct in C#
JaredPar
For this example your code works. But in a more abstract sample, it's possible for someone to overload == to not be reference identity (strings for instance). In that case null can be intepreted differently and give interesting results.
JaredPar
Yup, that's a fair point.
Jeff Yates
+2  A: 

Have Thing implement IComparable such that Things with null editDates have a higher order than those with an edit date. Then modify the sort expression to sort on the objects and not the edit dates.

Winston Smith
A: 

The answer from ffpf should work.

But if you have some time read through this great post about sorting with nulls from the BCL team

http://blogs.msdn.com/bclteam/archive/2008/10/06/the-compare-contract-kim-hamilton.aspx

Y Low