LINQ sorting using Lambda Expressions with dynamic field names
LINQ sorting using Lambda Expressions with dynamic field names
In this blog am going to explain you how sort the Linq collection by the dynamic field names
in order to archive this we nee to use reflection
Here is the small code block will overrides the order by functionality to pass filed names dymamically
public static IEnumerable<T> OrderBy<T>(
this IEnumerable<T> collection,
string columnName
)
{
ParameterExpression param = Expression.Parameter(typeof(T), "y"); // y
Expression property = Expression.Property(param, columnName); // y.ColumnName
Func<T, object> lambda = Expression.Lambda<Func<T, object>>( // y => y.ColumnName
Expression.Convert(property, typeof(object)),
param)
.Compile();
Func<IEnumerable<T>, Func<T, object>, IEnumerable<T>> expression = (c, f) => c.OrderBy(f);
IEnumerable<T> sortedlist = expression(collection, lambda);
return sortedlist;
}
Based on the above function we can use as bellow
IEnumerable<T> Mylist= ...
IEnumerable<T> orderedList = Mylist.OrderBy("PropName");
Hope this will helps you