- Create class LinqDynamicMultiSorting,
- public static class LinqDynamicMultiSorting
- {
- /// <summary>
- /// 1. The sortExpressions is a list of Tuples, the first item of the
- /// tuples is the field name,
- /// the second item of the tuples is the sorting order (asc/desc) case sensitive.
- /// 2. If the field name (case sensitive) provided for sorting does not exist
- /// in the object,
- /// exception is thrown
- /// 3. If a property name shows up more than once in the "sortExpressions",
- /// only the first takes effect.
- /// </summary>
- public static IEnumerable < T > MultipleSort < T > (this IEnumerable < T > data,
- List < Model.GridSort > gridsorts)
- {
- var sortExpressions = new List < Tuple < string,
- string >> ();
- for (int i = 0; i < gridsorts.Count(); i++)
- {
- var fieldName = gridsorts[i].Field.Trim();
- var sortOrder = (gridsorts[i].Dir.Length > 1) ?
- gridsorts[i].Dir.Trim().ToLower() : "asc";
- sortExpressions.Add(new Tuple < string, string > (fieldName, sortOrder));
- }
- // No sorting needed
- if ((sortExpressions == null) || (sortExpressions.Count <= 0))
- {
- return data;
- }
- // Let us sort it
- IEnumerable < T > query = from item in data select item;
- IOrderedEnumerable < T > orderedQuery = null;
- for (int i = 0; i < sortExpressions.Count; i++)
- {
- // We need to keep the loop index, not sure why it is altered by the Linq.
- var index = i;
- Func < T, object > expression = item => item.GetType()
- .GetProperty(sortExpressions[index].Item1)
- .GetValue(item, null);
- if (sortExpressions[index].Item2 == "asc")
- {
- orderedQuery = (index == 0) ? query.OrderBy(expression) :
- orderedQuery.ThenBy(expression);
- } else
- {
- orderedQuery = (index == 0) ? query.OrderByDescending(expression) :
- orderedQuery.ThenByDescending(expression);
- }
- }
- query = orderedQuery;
- return query;
- }
- }
- Create Second class GridSort,
- public class GridSort
- {
- public string Field
- {
- get;
- set;
- }
- public string Dir
- {
- get;
- set;
- }
- }
- Get data,
- List<Student> data = new List<Student>();
- data = GetStudentData();
- List<GridSort> sort = new List<GridSort>()
- sort = List of sort Expression
- Apply sorting on data,
- data.MultipleSort(sort)
Dynamic LINQ Multi Sorting
In this blog you will learn about dynamic LINQ multi sorting.
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

NGUYEN ANHANHPosted Feb 17, 2022, 12:45 AM
Thank you very much.
Former memberPosted Mar 31, 2018, 9:37 AM
Nice article, but i need to queryable objects for dynamic sorting ,please help