【问题标题】:Linq to SQL any from Enumerable来自 Enumerable 的 Linq to SQL any
【发布时间】:2017-04-16 18:09:45
【问题描述】:

我正在为我们的应用程序开发搜索引擎。 用户应该能够找到包含更多单词或任何这些单词的项目。用户可以使用“查找包含所有单词的位置”或“查找包含任何单词的位置”。

我正在使用 C# 4.6.2 和 LINQ to SQL。

代码类似于:

var words = userInput.Split(' '); // can be something like "Hi all"
var result = selection.Where(q => words.Any(k => q.Name.Contains(k)));

在这种情况下,用户想要查找包含“Hi”或“all”的项目

当我尝试遍历结果时,我得到了这个异常: 本地序列不能在查询运算符的 LINQ to SQL 实现中使用,包含运算符除外

你知道什么是最好的方法吗?

谢谢 雅库布

【问题讨论】:

标签: c# linq linq-to-sql


【解决方案1】:

我查看了建议的解决方案,我更喜欢在服务器端进行搜索。所以我决定使用表达式树来创建稳健的查询。

ParameterExpression pe = Expression.Parameter(typeof(Address), "findingSource");
Expression left = Expression.Property(pe, "Name");
Expression right = Expression.Constant(words[0]);
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
Expression expression = Expression.Call(left, method, right);
var result = expression;

for (var i = 1; i < words.Count; i++)
{
    left = Expression.Property(pe, "Name");
    right = Expression.Constant(words[i]);
    method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    expression = Expression.Call(left, method, right);

    result = Expression.OrElse(result, expression);
}

MethodCallExpression whereCallExpression = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { selection.ElementType },
    selection.Expression,
    Expression.Lambda<Func<Address, bool>>(result, new ParameterExpression[] { pe }));

return selection.Provider.CreateQuery<Address>(whereCallExpression);

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多