我实现了扩展方法来规范化这篇文章中描述的字符串:LINQ Where Ignore Accentuation and Case
如果我这样做的话,这个方法就像一个魅力:
employee.AsQueryable().Where(t=>t.Text.ToLower().RemoveDiacritics().Contains("ced"));
现在,我想通过动态生成 where 子句的谓词来更通用地使用它。
var values = filters.Select(f => f.Value is string && f.IgnoreAccent
?((string)f.Value).RemoveDiacritics()
:f.Value).ToArray();
// Create a predicate expression
string predicate = filter.ToExpression(filters);
// Use the Where method of Dynamic Linq to filter the data
queryable = queryable.Where(predicate, values);
谓词看起来像这样:
(Text.ToLower().RemoveDiacritics().Contains(@0))
由于未知原因,执行时出现以下错误消息:
No applicable method 'RemoveDiacritics' exists in type 'String'
但是,如果我在其他地方使用这个方法,它实际上工作得很好。
知道这里出了什么问题吗?
请注意,ToLower()
在这种情况下就像一个魅力。
预先感谢您的帮助!
编辑
这里是扩展方法的定义:
public static class StringExtension
{
public static string RemoveDiacritics(this String s)
{
String normalizedString = s.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < normalizedString.Length; i++)
{
Char c = normalizedString[i];
if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
stringBuilder.Append(c);
}
return stringBuilder.ToString();
}
}
最佳答案
Dynamic Linq 不支持扩展方法。 这样做的原因是Dynamic Linq使用了反射,很难找到扩展方法的实现,并使用反射来调用它。因此,动态 Linq 的作者并没有为此烦恼。
因此,您必须像调用常规静态方法一样调用扩展方法:
var values = filters.Select(f => f.Value is string && f.IgnoreAccent
?StringExtensions.RemoveDiacritics((string)f.Value)
:f.Value).ToArray();
关于c# - 在 linq 查询中使用 C# 扩展方法作为谓词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33528570/