有没有办法在 linq 查询中参数化方法

本文关键字:参数 方法 查询 linq 有没有 | 更新日期: 2023-09-27 18:37:11

在我的 Linq to SQL 应用程序中,用户可以搜索文本。星号 (*) 可用于搜索表达式的开头和/或结尾。现在的代码是这样的:

var search = SearchTextBox.Text.Trim();
bool filterStartsWith = false, filterEndsWith = false;
if (!string.IsNullOrEmpty(search))
{
    filterStartsWith = search.EndsWith("*");
    filterEndsWith = search.StartsWith("*");
    if (filterStartsWith) search = search.Substring(0, search.Length - 1);
    if (filterEndsWith) search = search.Substring(1);
    if (filterStartsWith)
    {
        if (filterEndsWith)
        {
            query = query.Where(item => item.Omschrijving.Contains(search));
        }
        else
        {
            query = query.Where(item => item.Omschrijving.StartsWith(search));
        }
    }
    else
    {
        if (filterEndsWith)
        {
            query = query.Where(item => item.Omschrijving.EndsWith(search));
        }
        else
        {
            query = query.Where(item => item.Omschrijving == search);
        }
    }
}

但是,我想概括一下,因为这种搜索发生在更多的地方。此外,在某些表上,这应该发生在多个列上。有什么想法吗?

我将Visual Studio 2010与.NET Framework 4.0一起使用。

有没有办法在 linq 查询中参数化方法

你可以试试这个:

static IQueryable<T> WhereColumnContains<T>(this IQueryable<T> source, Expression<Func<T, string>> selector, string search)
{
    if (string.IsNullOrWhiteSpace(search))
    {
        return source;
    }
    Expression<Func<T, bool>> expression;
    search = search.Trim();
    var filterStartsWith = search.EndsWith("*");
    var filterEndsWith = search.StartsWith("*");
    if (filterEndsWith) search = search.Substring(1);
    if (filterStartsWith)
    {
        search = search.Substring(0, search.Length - 1);
        if (filterEndsWith)
        {
            var parameter = Expression.Parameter(typeof(T), "parameter");
            expression = Expression.Lambda<Func<T, bool>>(
                Expression.Call(Expression.Invoke(selector, parameter), typeof(string).GetMethod("Contains", new[] { typeof(string) }), Expression.Constant(search)),
                parameter);
        }
        else
        {
            var parameter = Expression.Parameter(typeof(T), "parameter");
            expression = Expression.Lambda<Func<T, bool>>(
                Expression.Call(Expression.Invoke(selector, parameter), typeof(string).GetMethod("StartsWith", new[] { typeof(string) }), Expression.Constant(search)),
                parameter);
        }
    }
    else
    {
        if (filterEndsWith)
        {
            var parameter = Expression.Parameter(typeof(T), "parameter");
            expression = Expression.Lambda<Func<T, bool>>(
                Expression.Call(Expression.Invoke(selector, parameter), typeof(string).GetMethod("EndsWith", new[] { typeof(string) }), Expression.Constant(search)),
                parameter);
        }
        else
        {
            var parameter = Expression.Parameter(typeof(T), "parameter");
            expression = Expression.Lambda<Func<T, bool>>(
                Expression.Equal(Expression.Invoke(selector, parameter), Expression.Constant(search)),
                parameter);
        }
    }
    return source.Where(expression);
}

按如下方式调用它:

query = query.WhereColumnContains(item => item.Omschrijving, search);

您可以使用策略模式。您将有 4 个基于"搜索"值和"bool CanHandle(search)"方法的策略,一个工厂创建一个策略列表,你的程序将调用一个客户端,该客户端只是创建一个新工厂,调用一个方法 "BuildQuery(search)",执行使用 CanHandle 方法找到的正确策略,并返回一个查询值。

http://en.wikipedia.org/wiki/Strategy_pattern

您可以使用动态构建的表达式。

这是一个在多个列上实现 StartWith 的示例代码(可能无法编译,我直接在 stackoverflow 中键入它)- 只需添加对其他方法的支持......

此代码适用于所有 linq-to-sql 查询,假设"columnsToSearch"始终引用字符串属性。

IQueryable myQuery = ... your query you want to filter ...;
string searchWhat = "text to search";
bool startsWith;
Expression condition = null;
var p = Expression.Parameter(myQuery.ElementType,"x");
foreach (string column in columnsToSearch)
{
    if (startsWith)
    {
        var myCondition = Expression.Call(Expression.PropertyOrField(p, column),
                          typeof (string).GetMethod("StartsWith"),
                          Expression.Constant(searchWhat));
        if (condition == null)
            condition = myCondition;
        else
            condition = Expression.OrElse(condition, myCondition);
     }
 }
 var newQuery = Expression.Call(typeof (Queryable).GetMethod("Where"), myQuery.Expression, Expression.Lambda(condition, p));
 var myQueryFiltered = myQuery.Provider.CreateQuery(newQuery);

简而言之,如果您有查询 myRepository.Where(t=>t.Mycondition)此代码将生成一个新查询,例如 myRepository.Where(t=>t.Mycondition).Where(t=>t.Field1.StartsWith("a")||t.Field2.StartWith("a"))(当然取决于您提供给它的列)

然后,您所要做的就是将"myQueryFiltered"投射回IEnumerable或IQueryable,以便执行它并获得过滤结果:)