0

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

3 Answers 3

1
lstObjs.Sort((a,b) => Comparer.Default.Compare(a.FieldA, b.FieldA)); 
Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks. so that takes care of potentially null fields. What about sorting on multiple fields ...?
0

If FieldA is a string, you can perhaps use the null coalescing operator like so:

lstObjs.Sort((a,b)=> (a.FieldA ?? "").CompareTo(b.FieldA); 

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.