我想用*搜索。 我有
<asp:TextBox runat="server" Width="500" Height="20" ID="tbInfo"></asp:TextBox>
搜索方法:当我搜索没有星号*是正常搜索时,但是当我设置星号* LINQ查询时,如tbInfo.Contains()
示例:
I set in textbox: Michael - 1 result,
I set in textbox: Michael* - 20 results
我希望有人了解我。 10X
答案 0 :(得分:2)
你必须自己做一些编码。
示例查询:
var q = (from c in db.Customers
where c.CompanyName.Contains(name)
select c)
.ToList();
以上示例将始终在CompanyName中的任何位置搜索a 比赛。但是你需要让你的用户更多地控制它 匹配方法允许它们在任一处提供通配符 要匹配的文本的开头或结尾。这意味着你要离开 根据的存在和位置动态构建您的查询 外卡人物。
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
public static class LinqExtensions
{
public static IQueryable<TSource> WhereLike<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, string>> valueSelector,
string value,
char wildcard)
{
return source.Where(BuildLikeExpression(valueSelector, value, wildcard));
}
public static Expression<Func<TElement, bool>> BuildLikeExpression<TElement>(
Expression<Func<TElement, string>> valueSelector,
string value,
char wildcard)
{
if (valueSelector == null)
throw new ArgumentNullException("valueSelector");
var method = GetLikeMethod(value, wildcard);
value = value.Trim(wildcard);
var body = Expression.Call(valueSelector.Body, method, Expression.Constant(value));
var parameter = valueSelector.Parameters.Single();
return Expression.Lambda<Func<TElement, bool>>(body, parameter);
}
private static MethodInfo GetLikeMethod(string value, char wildcard)
{
var methodName = "Contains";
var textLength = value.Length;
value = value.TrimEnd(wildcard);
if (textLength > value.Length)
{
methodName = "StartsWith";
textLength = value.Length;
}
value = value.TrimStart(wildcard);
if (textLength > value.Length)
{
methodName = (methodName == "StartsWith") ? "Contains" : "EndsWith";
textLength = value.Length;
}
var stringType = typeof(string);
return stringType.GetMethod(methodName, new Type[] { stringType });
}
}
WhereLike扩展方法的用法如下:
var searchTerm = "*Inc";
var q = db.Customers
.WhereLike(c => c.CompanyName, searchTerm, '*')
.ToList();
找到了here的来源。