Reputation: 6903
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
Upvotes: 0
Views: 554
Reputation: 6903
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
Upvotes: 0
Reputation: 158309
If FieldA
is a string, you can perhaps use the null coalescing operator like so:
lstObjs.Sort((a,b)=> (a.FieldA ?? "").CompareTo(b.FieldA);
Upvotes: 0
Reputation: 1038850
lstObjs.Sort((a,b) => Comparer.Default.Compare(a.FieldA, b.FieldA));
Upvotes: 1