Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Dynamic LINQ Multi Sorting
WhatsApp
Kuldeep Patel
8y
35.5
k
0
4
25
Blog
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
LINQ
Multi Sorting
Up Next
LINQ Transaction, Commit And Roll Back
Ebook Download
View all
Printing in C# Made Easy
Read by 22.3k people
Download Now!
Learn
View all
Membership not found