using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using dynamic = System.Linq.Dynamic;
using System.Linq.Expressions;
namespace Project.Lib.Extensions
{
public static partial class Utils
{
public static List<T> SortForMe<T>(this List<T> list, string propertyName,SortDirection sortDirection)
{
string exp1 = string.Format("model.{0}", propertyName);
var p1 = Expression.Parameter(typeof(T), "model");
var e1 = dynamic.DynamicExpression.ParseLambda(new[] { p1 }, null, exp1);
if (e1 != null)
{
if (sortDirection==SortDirection.Ascending)
{
var result = list.OrderBy((Func<T, object>)e1.Compile()).ToList();
return result;
}
else
{
var result = list.OrderByDescending((Func<T, object>)e1.Compile()).ToList();
return result;
}
}
return list;
}
}
}
I am using this code for sorting my Generic List by propertyName. When the property type is string
, this code runs successfully, but when the type is long
or int
, I am getting this exception:
Unable to cast object of type 'System.Func`2[Project.Lib.Model.UserQueryCount,System.Int64]' to type 'System.Func`2[Project.Lib.Model.UserQueryCount,System.Object]'.
var result = list.OrderBy((Func<T, dyamic>)e1.Compile()).ToList();
In the line above, I decided using dynamic
, but got the exception again. What should I do?
I changed my method like this:
public static List<TModel> SortForMe<TModel>(this List<TModel> list, string propertyName,SortDirection sortDirection) where TModel:class
{
var ins = Activator.CreateInstance<TModel>();
var prop= ins.GetType().GetProperty(propertyName);
var propertyType = prop.PropertyType;
string exp1 = string.Format("model.{0}", propertyName);
var p1 = System.Linq.Expressions.Expression.Parameter(typeof(TModel), "model");
var e1 = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p1 }, null, exp1);
if (e1 != null)
{
if (sortDirection==SortDirection.Ascending)
{
return list.OrderBy((Func<TModel, propertyType>)e1.Compile()).ToList();
}
return list.OrderByDescending((Func<TModel, propertyType>)e1.Compile()).ToList();
}
return list;
}
I got propertyType using reflection but in Func I couldn't use it like this: "Func<TModel, propertyType>"
Is there any way to resolve this problem
Thanks for the help.