Click here to Skip to main content
11,495,869 members (58,969 online)
Click here to Skip to main content

Generic Sorting with LINQ and Lambda Expressions

, 24 Jun 2009 CPOL 60.1K 31
Rate this:
Please Sign up or sign in to vote.
This class sorts objects using Generics and LINQ Lambda Expressions.


Sorting objects has been a programming problem that has gone from a science to a mere few lines of code. Though it does not take nearly the amount of consideration as it did before my time in the industry, it's still just as relevant. This article takes a look at sorting using Lambda Expressions and Generics. In my opinion, the best technique for sorting objects that I have seen so far. This class has found a definite home in my Utils assembly, and so I share it with you.


As programmers, it is always our duty, and pleasure, to find better ways to the same thing. That is how I stumbled on this sorting technique. I was working on a project that had several grids that required paging and sorting, and like many projects, we were using an object model. I was thinking that I wanted a generic sorting class that did all the work in one place, and this article shares the results.

Using the code

These samples have been dumped down a little from my actual implementation to improve readability for the purposes of this article. After reviewing this code though, I am confident that you will be able to think of several slick uses for this technique like I have.

Usage of the sorting class


GenericSorter<surveystateformatdata> gs = new GenericSorter<surveystateformatdata >();
SurveyStateFormatItems = gs.Sort(SurveyStateFormatItems.AsQueryable, 
                                 sortExpression, sortDirection).ToArray();


Dim gs As New GenericSorter(Of SurveyStateFormatData)
SurveyStateFormatItems = gs.Sort(SurveyStateFormatItems.AsQueryable, _
                                 sortExpression, sortDirection).ToArray()

Here is the sorting class:


using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Linq.Expressions; 

public class GenericSorter<T>
    public IEnumerable<T> Sort(IEnumerable<T> source, string sortBy, string sortDirection)
        var param = Expression.Parameter(typeof(T), "item");

        var sortExpression = Expression.Lambda<Func<T, object>>
            (Expression.Convert(Expression.Property(param, sortBy), typeof(object)), param);

        switch (sortDirection.ToLower())
            case "asc":
                return source.AsQueryable<T>().OrderBy<T, object>(sortExpression);
                return source.AsQueryable<T>().OrderByDescending<T, object>(sortExpression);



Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Linq.Expressions

Public Class GenericSorter(Of T)

    Public Function Sort(ByVal source As IEnumerable(Of T), _
                         ByVal sortBy As String, _
                         ByVal sortDirection As String) As IEnumerable(Of T)

        Dim param = Expression.Parameter(GetType(T), "item")

        Dim sortExpression = Expression.Lambda(Of Func(Of T, Object))_
        (Expression.Convert(Expression.[Property](param, sortBy), _
        GetType(Object)), param)

        Select Case sortDirection.ToLower
            Case "asc"
                Return source.AsQueryable().OrderBy(sortExpression)
            Case Else
                Return source.AsQueryable().OrderByDescending(sortExpression)
        End Select

    End Function

End Class


  • Article added: (06/22/2009).


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Web Developer
United States United States
No Biography provided
Follow on   Twitter

Comments and Discussions

GeneralUpdated to Extension Method Pin
Nipesh Shah12-Mar-14 5:44
memberNipesh Shah12-Mar-14 5:44 
QuestionKeep getting exception Pin
DingHaobo5-Mar-14 4:17
memberDingHaobo5-Mar-14 4:17 
QuestionHow to sort a Collection base on a given dynamic sort field string list Pin
Member 412087022-Nov-12 16:18
memberMember 412087022-Nov-12 16:18 
AnswerRe: How to sort a Collection base on a given dynamic sort field string list Pin
AdamNThompson3-Dec-12 5:05
memberAdamNThompson3-Dec-12 5:05 
QuestionPerformance Pin
rickoshay29-Jun-09 10:39
memberrickoshay29-Jun-09 10:39 
AnswerRe: Performance Pin
AdamNThompson30-Jun-09 9:27
memberAdamNThompson30-Jun-09 9:27 
GeneralThis is a neat concept, but example does not compile. Pin
Michael Lee Yohe23-Jun-09 10:21
memberMichael Lee Yohe23-Jun-09 10:21 
GeneralRe: This is a neat concept, but example does not compile. Pin
AdamNThompson23-Jun-09 12:20
memberAdamNThompson23-Jun-09 12:20 
I created the C# example with a code converter as the project I developed this in was in VB.NET. I will run sime test and update the article. But I think it might should be something like this in C#.

return source.AsQueryable<T>().OrderBy<T, object>(sortExpression);

-Adam N. Thompson

GeneralFigured it out with some modifications to the C# version: Pin
Michael Lee Yohe23-Jun-09 12:43
memberMichael Lee Yohe23-Jun-09 12:43 
GeneralRe: Figured it out with some modifications to the C# version: Pin
AdamNThompson23-Jun-09 13:01
memberAdamNThompson23-Jun-09 13:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 24 Jun 2009
Article Copyright 2009 by AdamNThompson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid