无法将类型'System.String'强制转换为'System.Object'类型

时间:2014-02-26 04:58:56

标签: c# lambda

我正在尝试使用lambda Expression对Users进行排序。我的用户类

public class Users
{
        public long Id { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DateCreated { get; set; }
}

我的排序方法

public List<Users> SortUsers(string sSortBy)
{
    var arg = Expression.Parameter(typeof(Users), "Users");
    var body = Expression.Convert(Expression.Property(arg, sSortBy), typeof(object));
    var lambda = Expression.Lambda<Func<Users, object>>(body, arg);

    List<Users> UserList;
    UserList = UOWUser.UsersRepository.Entities.OrderBy(lambda).ToList(); // Error here
    return UserList;
}

我正在通过

访问该方法
List<Users> UserList;
UserList = objUsers.SortUsers("FirstName");

我正在sSortBy传递string(此处为“FirstName”)

  

错误:无法将类型'System.String'强制转换为'System.Object'。

排队UserList = UOWUser.UsersRepository.Entities.OrderBy(lambda).ToList();

修改

public List<Users> SortUsers(string sSortBy)
{
    var arg = Expression.Parameter(typeof(Users), "Users");
    var TType = Expression.Property(arg, sSortBy).Type;
    var body = Expression.Convert(Expression.Property(arg, sSortBy), TType);
    var lambda = Expression.Lambda<Func<Users, object>>(body, arg);// Error here  :: Expression of type 'System.DateTime' cannot be used for return type 'System.Object'   
    List<Users> UserList;
    UserList = UOWUser.UsersRepository.Entities.OrderBy(lambda).ToList(); 
    return UserList;
}

UserList = objUsers.SortUsers("FirstName");一起正常工作,但在UserList = objUsers.SortUsers("DateCreated");

时出现错误
  

'System.DateTime'类型的表达式不能用于返回类型   'System.Object的'

任何帮助将不胜感激谢谢

1 个答案:

答案 0 :(得分:1)

检查一下:

public static List<Users> SortUsers(string sSortBy)
{
    var arg = Expression.Parameter(typeof(Users), "Users");
    var sortProperty = Expression.Property(arg, sSortBy);
    var lambda = Expression.Lambda(sortProperty, arg);

    var param = Expression.Parameter(typeof(IQueryable<Users>));
    var orderByCall = Expression.Call(typeof(Queryable), "OrderBy", new Type[] { typeof(Users), sortProperty.Type }, new Expression[] { param, lambda });
    var orderLambda = Expression.Lambda<Func<IQueryable<Users>, IQueryable<Users>>>(orderByCall, param).Compile();

    List<Users> UserList;
    UserList = orderLambda(UOWUser.UsersRepository.Entities).ToList(); // Error here
    return UserList;
}

它使整个source.OrderBy(x => x.PropName)Expression,因此您无需实际指定x.PropName类型。