Using sorting functions with Linq for Objects

If you have written Linq queries, you are familiar with OrderBy clause.  Here is a quick example:

from one in selected
select one).OrderBy(one => one.Name)

If you only need to sort by single field, or even many fields, you are OK.  Here is an example:

from one in selected select one).OrderBy(one => one.Name).ThenBy(one=>one.Title)

But what if you would like to sort by something more complicated, such as sum of Salary + Bonus in descending order, or even something more complex that that.  Well, you can use a delegate that Linq provides for sorting:

return (from one in selected
select one).OrderBy(one => SortFunction(one))
     //descending sort
return (-returnValue);
private double SortFunction(MyObject member)
     double returnValue = member.Salary + member.Bonus;


The only catch your function must return the type that implements IComparable,which all primitive types do.  You can actually even use a custom return types and use an additional OrderBy overload that accepts another parameter – custom comparer.

You can also do something very similar in Where clause that also accepts delegates.  Pretty impressive if you ask me.

Leave a Reply

Your email address will not be published. Required fields are marked *