Dynamic Sorting based on Enum and Dropdown

Published on Friday, 6 January 2017

I come across many situations when I have multiple sort conditions, based on an enum, and I wanted a dynamic way of doing it without having to write a case statement to deal with it.

This, only works if your properties match up with the enum values, but that is usually the case I find.

Here is the Enum:

public enum SortBy
{
	Option1 = 1,
	Option2 = 2,
	Option3 = 3
}

Here is the Custom Class

private class CustomGrid
{
	public string Option1 { get; set; }
	public string Option2 { get; set; }
	public string Option3 { get; set; }
}

Here is the sort Code:

private IQueryable SortDate(IQueryable Data)
{
	bool IsDesc = Convert.ToBoolean(Convert.ToInt32(ddlSortDir.SelectedValue));

	var propertyInfo = typeof(CustomGrid).GetProperty(ddlSortBy.SelectedItem.Value).Name;
	Data = Data.OrderByWithDirection(o => propertyInfo, isDescending);

	return pData;
}