Dynamic LINQ Multi Sorting
In this blog you will learn about dynamic LINQ multi sorting.
- Create class LinqDynamicMultiSorting,
- public static class LinqDynamicMultiSorting
- {
-
-
-
-
-
-
-
-
-
-
- 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));
- }
-
- if ((sortExpressions == null) || (sortExpressions.Count <= 0))
- {
- return data;
- }
-
- IEnumerable < T > query = from item in data select item;
- IOrderedEnumerable < T > orderedQuery = null;
- for (int i = 0; i < sortExpressions.Count; i++)
- {
-
- 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,