在使用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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句