Passing an anonymous type to the IEnumerable.OrderBy() lambda yields “System.ArgumentException: At least one object must implement IComparable.”

Sorting with LINQ: don’t use anonymous types

I got the error message "System.ArgumentException: At least one object must implement IComparable." today for the following, seemingly innocuous code.

var ordered = order.Lines.OrderBy(l => new { l.AdminCode, l.OrderLineNr});

I thought this was the way to do it; after, that’s the way that you use Join() for multiple properties. What it was however was a gap in my knowledge. The correct way to do it is:

var ordered = order.Lines.OrderBy(l => l.AdminCode).ThenBy(l => l.OrderLineNr);

This makes sense when you consider that the following are equivalent:

// methods, then LINQ syntax equivalent
var lines = order.Lines.OrderBy(l => l.AdminCode).ThenBy(l => l.OrderLineNr);
lines = from l in Lines orderby l.AdminCode, l.OrderLineNr select l;

// using a descending modifier
lines = order.Lines.OrderBy(l => l.AdminCode).ThenByDescending(l => l.OrderLineNr);
lines = from l in Lines orderby l.AdminCode, l.OrderLineNr descending select l;

Every time I use this kind of thing I consider what this would be if I needed to use an IComparer implementation, and become just that little bit happier.

No Comments

Post a Comment

Your email is never shared. Required fields are marked *