Click here to Skip to main content
15,881,803 members
Articles / Web Development / ASP.NET
Tip/Trick

How to sort a List of objects by property values

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
8 Jun 2012CPOL 12.8K   48   1  
How to sort a list of objects by property values.

Introduction

In this article we will look at one way you can sort a list of objects by property values. We will bind a List to a GridView and use GridView sorting to demo this. For the purposes of this article we will use error log details to display and sort in a GridView.

Step 1: Create a GridView that will display the error log

XML
<asp:GridView ID="grdViewErrorLog" runat="server" AutoGenerateColumns="False" 
        BackColor="White" BorderColor="#999999" BorderStyle="Solid"  
        CellPadding="5" ForeColor="Black" GridLines="Both"  
        AllowPaging="False"   CellSpacing="1"  EmptyDataText="No Error Log found"
        RowStyle-CssClass="smallRow"
        AlternatingRowStyle-CssClass="smallRow"
        AllowSorting="true" onsorting="grdViewErrorLog_Sorting" >
    <FooterStyle BackColor="#CCCCCC" />
    <Columns>
    <asp:BoundField HeaderText="RecordId" DataField="RecordId"  SortExpression="RecordId"/>
    <asp:BoundField HeaderText="DateTimeCreated" DataField="DateTimeCreated"  SortExpression="DateTimeCreated"/>
    <asp:BoundField HeaderText="CreatedBy" DataField="CreatedBy"  SortExpression="CreatedBy"/>
    <asp:BoundField HeaderText="ErrorDetail" DataField="ErrorDetail"  SortExpression="ErrorDetail"/>
    </Columns>
    <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
    <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#E6EEEE" Font-Bold="True" ForeColor="Black" Font-Size="10"/>
</asp:GridView>

Step 2: Create an ErrorLog class

C#
public class ErrorLog
{
    private int _recordId;
    private DateTime _dateTimeCreated;
    private string _createdBy;
    private string _errorDetail;

    public int RecordId { get { return _recordId; } set { _recordId = value; } }
    public DateTime DateTimeCreated { get { return _dateTimeCreated; } set { _dateTimeCreated = value; } }
    public string CreatedBy { get { return _createdBy; } set { _createdBy = value; } }
    public string ErrorDetail { get { return _errorDetail; } set { _errorDetail = value; } }
}

Step 3: Create a List of error logs and fill it with dummy data

In real life you will have this data coming from some source. First we are creating an ErroLog list and then binding it to the GridView. We are keeping our data in Session for later use in sorting.

C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        List<ErrorLog> lstErrorLog = new List<ErrorLog>();
        // Just add some dummy data to list. This is dumb way to do it but will be OK for demo
        for (int i = 0; i < 10; i++)
        {
            ErrorLog objErrLog = new ErrorLog();
            objErrLog.RecordId = i;
            objErrLog.DateTimeCreated = DateTime.Now.AddDays(i);
            objErrLog.CreatedBy = "virang";
            objErrLog.ErrorDetail = "Error No " + i + " : Dummy Error";
            lstErrorLog.Add(objErrLog);
        }

        // Bind Error Log to gridview
        grdViewErrorLog.DataSource = lstErrorLog;
        grdViewErrorLog.DataBind();
        
        Session["ErrorLog"] = lstErrorLog;

        //Hold sort direction in session to keep track for each postback
        Session["SortDirection"] = "ASC"; 
    }
}

Step 4: Add GridView sorting event handler

C#
protected void grdViewErrorLog_Sorting(object sender, GridViewSortEventArgs e)
{
    if (Session["ErrorLog"] != null)
    {
        List<ErrorLog> selected = (List<ErrorLog>)Session["ErrorLog"];

        //This is where the magic of LINQ make it easier to sort List of Objects by its property
        var param = Expression.Parameter(typeof(ErrorLog), e.SortExpression);
        var sortExpression = Expression.Lambda<Func<ErrorLog, object>>(
            Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);

        //Check sort direction and revert it for next call ASC to DESC and DESC to ASC
        if (Session["SortDirection"] != null)
        {
            if (Session["SortDirection"].ToString() == "ASC")
            {
                var selectedNew = selected.AsQueryable<ErrorLog>().OrderBy(sortExpression);

                grdViewErrorLog.DataSource = selectedNew;
                grdViewErrorLog.DataBind();
                
                Session["SortDirection"] = "DESC";
            }
            else if (Session["SortDirection"].ToString() == "DESC")
            {
                var selectedNew = selected.AsQueryable<ErrorLog>().OrderByDescending(sortExpression);

                grdViewErrorLog.DataSource = selectedNew;
                grdViewErrorLog.DataBind();
               
                Session["SortDirection"] = "ASC";
            }
        }
    }
}

That is it. We have sorted the list of objects by its property using LINQ and Lambda Expressions. Happy coding!!!

License

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


Written By
Software Developer (Senior)
Australia Australia
I am currently working as a Software Developer in .NET technologies.

Languages & Technologies I have worked on so far:

Pascal ... My first programming language..baby steps..
8085 Assembler ... Amazing how it all works internally in computer brain... "intel inside"
C... missing my point(er)....
C++... Its all about classes ...
LISP ... Did I missed any parenthesis ?
VB... Oh dear... Just like a war stories.. those are the days
Java... I learn to program this in notepad...
C#... Oh what a smooth sailing...
ASP.NET... web is the future ...
Oracle ... Not the one from "The Matrix"...
MSSQL... select Programming from Universe where StartTime >='BigBang'
Wireless Sensor Networks ... Look who is talking too ?

Comments and Discussions

 
-- There are no messages in this forum --