gpt4 book ai didi

c# - 有没有办法在 linq 查询中参数化方法?

转载 作者:行者123 更新时间:2023-12-04 04:36:34 25 4
gpt4 key购买 nike

在我使用 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 一起使用。

最佳答案

你可以试试这个:

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);

关于c# - 有没有办法在 linq 查询中参数化方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19654754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com