Click here to Skip to main content
6,822,123 members and growing! (18,816 online)
Email Password   helpLost your password?
General Programming » Algorithms & Recipes » Sorting     Intermediate License: The Code Project Open License (CPOL)

Generic Sorting with LINQ and Lambda Expressions

By AdamNThompson

This class sorts objects using Generics and LINQ Lambda Expressions.
C#3.0, VB9.0, C#4.0, VB10.NET3.5, .NET4.0, LINQ, Dev
Revision:5 (See All)
Posted:22 Jun 2009
Updated:24 Jun 2009
Views:8,768
Bookmarked:27 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
3 votes for this article.
Popularity: 1.91 Rating: 4.00 out of 5

1

2
1 vote, 33.3%
3
1 vote, 33.3%
4
1 vote, 33.3%
5

Introduction

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.

Background

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

C#:

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

VB.NET:

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

Here is the sorting class:

C#:

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);
            default:
                return source.AsQueryable<T>().OrderByDescending<T, object>(sortExpression);

        } 
    }
}

VB.NET:

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

History

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

License

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

About the Author

AdamNThompson


Member
I am a .NET Developer for company that builds custom web applications. It's an interesting job because each site is different. We build anything that the mind can imagine, and the client can afford.

Fun stuff... Smile

CP is my favorite site for code samples, news, and articles. I like the community here and I like the fact that it mainly caters to developers using the .NET platform.
Occupation: Web Developer
Location: United States United States

Other popular Algorithms & Recipes articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh)FirstPrevNext
QuestionPerformance Pinmemberrickoshay10:39 29 Jun '09  
AnswerRe: Performance PinmemberAdamNThompson9:27 30 Jun '09  
GeneralThis is a neat concept, but example does not compile. PinmemberMichael Lee Yohe10:21 23 Jun '09  
GeneralRe: This is a neat concept, but example does not compile. PinmemberAdamNThompson12:20 23 Jun '09  
GeneralFigured it out with some modifications to the C# version: PinmemberMichael Lee Yohe12:43 23 Jun '09  
GeneralRe: Figured it out with some modifications to the C# version: PinmemberAdamNThompson13:01 23 Jun '09  
GeneralRe: Figured it out with some modifications to the C# version: PinmemberMichael Lee Yohe5:45 24 Jun '09  
GeneralRe: Figured it out with some modifications to the C# version: Pinmemberrxm02038:07 25 Jun '09  
GeneralRe: Figured it out with some modifications to the C# version: [modified] PinmemberSchmuli1:14 30 Jun '09  
GeneralRe: Figured it out with some modifications to the C# version: PinmemberSchmuli1:55 30 Jun '09  
GeneralRe: Figured it out with some modifications to the C# version: PinmemberAdamNThompson9:37 30 Jun '09  
GeneralRe: This is a neat concept, but example does not compile. PinmemberAdamNThompson12:49 23 Jun '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 24 Jun 2009
Editor: Smitha Vijayan
Copyright 2009 by AdamNThompson
Everything else Copyright © CodeProject, 1999-2010
Web22 | Advertise on the Code Project