对于那些像我一样在 LINQ 中寻找“SQL Like”方法的方法的人来说,我有一些非常好的东西。
我处于无法以任何方式更改数据库以更改列排序规则的情况。所以我必须在我的 LINQ 中找到一种方法来做到这一点。
我正在使用与SqlFunctions.PatIndex
真正的 SQL LIKE 运算符类似的辅助方法。
首先,我需要在搜索值中枚举所有可能的变音符号(我刚刚学过的一个词)以获得类似:
déjà => d[éèêëeÉÈÊËE]j[aàâäAÀÂÄ]
montreal => montr[éèêëeÉÈÊËE][aàâäAÀÂÄ]l
montréal => montr[éèêëeÉÈÊËE][aàâäAÀÂÄ]l
然后以 LINQ 为例:
var city = "montr[éèêëeÉÈÊËE][aàâäAÀÂÄ]l";
var data = (from loc in _context.Locations
where SqlFunctions.PatIndex(city, loc.City) > 0
select loc.City).ToList();
所以为了我的需要,我写了一个 Helper/Extension 方法
public static class SqlServerHelper
{
private static readonly List<KeyValuePair<string, string>> Diacritics = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("A", "aàâäAÀÂÄ"),
new KeyValuePair<string, string>("E", "éèêëeÉÈÊËE"),
new KeyValuePair<string, string>("U", "uûüùUÛÜÙ"),
new KeyValuePair<string, string>("C", "cçCÇ"),
new KeyValuePair<string, string>("I", "iîïIÎÏ"),
new KeyValuePair<string, string>("O", "ôöÔÖ"),
new KeyValuePair<string, string>("Y", "YŸÝýyÿ")
};
public static string EnumarateDiacritics(this string stringToDiatritics)
{
if (string.IsNullOrEmpty(stringToDiatritics.Trim()))
return stringToDiatritics;
var diacriticChecked = string.Empty;
foreach (var c in stringToDiatritics.ToCharArray())
{
var diac = Diacritics.FirstOrDefault(o => o.Value.ToCharArray().Contains(c));
if (string.IsNullOrEmpty(diac.Key))
continue;
//Prevent from doing same letter/Diacritic more than one time
if (diacriticChecked.Contains(diac.Key))
continue;
diacriticChecked += diac.Key;
stringToDiatritics = stringToDiatritics.Replace(c.ToString(), "[" + diac.Value + "]");
}
stringToDiatritics = "%" + stringToDiatritics + "%";
return stringToDiatritics;
}
}
如果你们中的任何人有改进这种方法的建议,我会很高兴听到你的声音。