How to sort a List of objects by property values
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
<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
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.
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
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!!!