I'm looking for a simple extension to the boilerplate syntax below which will allow sorting on one or more fields and also handle null values.
List<myObject> lstObjs = new List<myObject>();
//Assume this is populated with some instances of myObject - some of which will have null members
//e.g. myObject mo1 = new myObject(1, null, "MO1" null);
lstObjs.Sort((a,b)=> a.FieldA.CompareTo(b.FieldA);
Can anyone assist ...开发者_运维百科?
Thanks in advance,
5arx
lstObjs.Sort((a,b) => Comparer.Default.Compare(a.FieldA, b.FieldA));
If FieldA
is a string, you can perhaps use the null coalescing operator like so:
lstObjs.Sort((a,b)=> (a.FieldA ?? "").CompareTo(b.FieldA);
The answer above takes care of the nulls, but I think this is what I was looking for:
Generic List Sort on Multiple members
I need to check whether one can use an infinite number of .ThenBy statements but this aside it works for me.
Not sure whether it's SO ettiquette to answer one's own questions. Its definitely not good to ask a question for which their is already an answer on SO. Apologies, don't know how i missed it :-o
精彩评论