如何使用表达式参数扩展?

时间:2015-08-03 10:44:37

标签: c# asp.net entity-framework

如何使用此扩展程序?

public static IQueryable<TSource> MyOrderByType<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, string>> predicate)
{
    return condition ? source.OrderBy(predicate) : source.OrderByDescending(predicate);
}

我用这种方式:

using (var ctx = new MyEntities())
{
    result = ctx.Users
       .MyOrderByType(sortType,p=>sortKey)
        .ToList();                
}

搜索方法:

 public List<User> Search(string name, string sortKey, bool sortType)
{
    List<User> result;
     using (var ctx = new MyEntities())
            {
                result = ctx.Users
.where(u => u.name.contains(name))
.MyOrderByType(sortType, p => sortKey)
}
}
.ToList();

            }
            return result;
}
代码背后的

 bool sortType=ddlSortType.SelectedValue=="0"?true:false;
string sortKey=ddlSortKey.SelectedValue;
var lstUser = userService.Search(txtName.Text,sortType,sortKey);

但它没有对结果进行排序。

有什么问题?

1 个答案:

答案 0 :(得分:0)

因为你没有正确传递谓词。在调用MyOrderByType扩展程序时,您通常会选择要排序的User字段。使用sortKey字符串创建正确的谓词。我处理案例以解析名称和电子邮件的表达式,您可以轻松添加其他字段以进行排序。

var sortKey = "name"; // use your sortKey
Expression<Func<User, string>> sortExpression;
switch (sortKey)
{
    case "email":
        sortExpression = x => x.Email;
        break;
    case "name":
        sortExpression = x => x.Name;
        break;
    default:
        sortExpression = x => x.Name;
        break;
}

using (var ctx = new MyEntities())
{
    result = ctx.Users
       .MyOrderByType(sortType, sortExpression)
       .ToList();                
}

// defined below
public class User
{
    public string Name {get;set;}

    public string Email {get;set;}

    // other properties
}

public class MyEntities : DbContext 
{ 
    public DbSet<User> Users { get; set; }
}