C#Generic Linq查询

bog*_*dan 6 c# linq

我需要写一些通用的搜索方法,如下所示:

public List<T> Search<T>(SearchParamsBase searchParams)
{
    using (var context = new TestEntities())
    {
        var dataType = TypeMap.Get(typeof (T));
        var dataSet = context.Set(dataType);

        var searchQuery = CreateQuery((IEnumerable<object>) dataSet), searchParams)

        return searchQuery.ToList()
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个CreateQuery()应该过滤IEnumerable对象的函数.所有类别的此功能都不同.例如:

CreateQuery(IEnumerable<object> collection, SearchParamsBase searchParams)
{
    var search = (SomeSearchImplementation)searchParams;
    // filter 
    collection = collection.Where(x => x.Name == search.Name);
    // select page
    collection = collection.Skip(search.Page * search.CountPerPage);
    collection = collection.Take(search.CountPerPage);
    // order by and so on
    // ...
    return collection;
}
Run Code Online (Sandbox Code Playgroud)

我该如何正确实现这个想法?

Mar*_*lme 8

你基本上想要做的是动态构造LINQ查询.为此,您需要在运行时修改/构建表达式树.如果您不熟悉表达式树和Expression<T>类型,我推荐本文以及"另请参阅"部分中引用的页面:

http://msdn.microsoft.com/en-us/library/bb397951.aspx

现在您已经掌握了基本概念,让我们实现动态排序.下面的方法是一个扩展,IQueryable<T>这意味着它不仅适用于列表,而且适用于每个LINQ数据源,因此您也可以直接对数据库使用它(在分页和排序方面比在内存操作中更有效).该方法采用您要排序的属性名称和排序方向(升序/降序):

public static IQueryable<T> OrderByDynamic<T>(this IQueryable<T> query, string sortColumn, bool descending) 
{
    // Dynamically creates a call like this: query.OrderBy(p => p.SortColumn)
    var parameter = Expression.Parameter(typeof(T), "p");

    string command = "OrderBy";

    if (descending)
    {
        command = "OrderByDescending";
    }

    Expression resultExpression = null;    

    var property = typeof(T).GetProperty(sortColumn);
    // this is the part p.SortColumn
    var propertyAccess = Expression.MakeMemberAccess(parameter, property);

    // this is the part p => p.SortColumn
    var orderByExpression = Expression.Lambda(propertyAccess, parameter);

    // finally, call the "OrderBy" / "OrderByDescending" method with the order by lamba expression
    resultExpression = Expression.Call(typeof(Queryable), command, new Type[] { typeof(T), property.PropertyType },
       query.Expression, Expression.Quote(orderByExpression));

    return query.Provider.CreateQuery<T>(resultExpression);
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以编写代码订购酒店所数据集Nameascending顺序:

dataSet.OrderByDynamic("Name", false)
Run Code Online (Sandbox Code Playgroud)

为动态过滤创建扩展方法遵循相同的模式.如果你理解上面的代码,那对你来说就没问题了.