TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Dynamic LINQ Multi Sorting
Kuldeep Patel
Jun 16, 2016
35.2
k
0
4
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
In this blog you will learn about dynamic LINQ multi sorting.
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
LINQ
Next Recommended Reading
LINQ Transaction, Commit And Roll Back