我正在将 ASP.NET MVC5 与 Entity Framework 6、SQL Server 2012 一起使用,目前在我为我的数据返回 Iqueryable 然后调用 tolist 之后,我调用了我的字符串扩展名,该扩展名应用了用户搜索查询。我想将此应用于 Iqueryable aka sql 查询本身或以另一种方式获得类似的功能。目前用户可以无序搜索单词,他们可以使用引号来按顺序搜索整个文本集,并带有空格。如果他们不知道某个数字或字母,他们也可以使用通配符。
这是我的字符串扩展
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
namespace casey.Helpers
{
public static class SearchStringExtension
{
public static bool Like(this string str, string value)
{
List<string> formatedsearch = new List<string>();
string searchForNext = ("");
string searchForx = value;
searchForx = searchForx.ToUpper();
searchForx = searchForx.Replace("\\", @"\\");
searchForx = searchForx.Replace("*", @"\*").Replace("+", @"\+").Replace(":", @"\:").Replace("#", @"\#");
searchForx = searchForx.Replace("(", @"\(").Replace(")", @"\)").Replace("<", @"\<").Replace(">", @"\>");
searchForx = searchForx.Replace("{", @"\{").Replace("}", @"\}").Replace("[", @"\[").Replace("]", @"\]");
searchForx = searchForx.Replace("=", @"\=").Replace("-", @"\-").Replace("_", @"_").Replace("%", @"\%");
searchForx = searchForx.Replace("|", @"\|").Replace("!", @"\!").Replace("^", @"\^").Replace("%", @"\%");
searchForx = searchForx.Replace(".", @"\.");
searchForx = searchForx.Replace("?", ".");
string s = searchForx;
//find all words with quotes around them
//example search string equals I "Like" Fish.
//asigns Like to rgx
Regex rgx = new Regex("\"(.+?)\"");
s = "^";
// add regular and expression with ignore of all charactes before clause to all quoted words and and clause
//example ^(?.*Like)
foreach (Match match in rgx.Matches(searchForx))
{
s += "(?=.*" + match.Value.Trim('"') + ")";
}
//example I "Like" Fish. becomes I Fish
searchForNext = Regex.Replace(searchForx, "\"(.+?)\"", "");
//this formats regular non quoted part of string
char[] delimiter1 = new char[] { ' ' };
formatedsearch = searchForNext.Split(delimiter1, StringSplitOptions.RemoveEmptyEntries).ToList();
//example I Fish becomes ^(?.*Like)(?=.*I)(?=.*Fish)
foreach (string searchvalue in formatedsearch)
{
s += "(?=.*" + searchvalue + ")";
}
//this ignores case and ignores endline characters
if (!string.IsNullOrEmpty(str))
{
Regex r = new Regex(s, RegexOptions.Singleline);
if (r.IsMatch(str.ToUpper()))
return true;
}
return false;
}
}
}