LINQ和正则表达式 [英] LINQ and Regular expressions
问题描述
为什么我不能删除以下代码中的(无用)行?如果保留它,则可以得到预期的结果.如果没有,我得到
方法``System.Text.RegularExpressions.Match Match(System.String,System.String)''不支持SQL转换.
谢谢
Why is it that I can''t remove the (useless) line in the following code? If I leave it in, I get the expected results. If not, I get
Method ''System.Text.RegularExpressions.Match Match(System.String, System.String)'' has no supported translation to SQL.
Thanks
string[] aa = { "X" };
var q =
from a in aa /// USELESS
from translation in db.ExternalNames
let t = translation.name
where Regex.Match("XYZ", translation.External).Success
select new {t};
为了澄清起见,该表包含诸如(X. *,foo)之类的对,并且给定"XYZ",我想检索foo.同样,使用无用的行也可以正常工作.
[edit]添加了代码块-OriginalGriff [/edit]
For clarification, the table contains pairs such as (X.*, foo) and, given "XYZ" I want to retrieve foo. Again, with the useless line it works fine.
[edit]Code block added - OriginalGriff[/edit]
推荐答案
而没有看到ExternalNames
中的数据,我想您总是希望得到结果.由于包含了AA(使用from,而不是join),因此您将拥有笛卡尔积,因此即使正则表达式不匹配,也将始终有结果.
Without seeing the data in ExternalNames
I would guess that you always expect to have results. Since AA is included (with from, not join) you will have a cartesian product so you will always have a result even if the regular expression does not match.
我不知道可以肯定,但是我怀疑字符串数组和您的数据库实体的笛卡尔乘积意味着整个查询是一个Linq-to-objects查询,并强制立即对该查询的Linq-to-SQL部分进行求值.
我认为此查询可能等同于以下内容:
I don''t know for sure, but I suspect that the Cartesian product of the string array and your database entities means the entire query is a Linq-to-objects query and forces the Linq-to-SQL part of the query to be evaluated right away.
Here''s what I think this query might be equivalent to:
string[] aa = { "X" };
var q =
from a in aa /// USELESS
from translation in db.ExternalNames.ToList() // <-- The ToList() call forces immediate evaluation.
let t = translation.name
where Regex.Match("XYZ", translation.External).Success
select new {t};
您可以通过查看Reflector或其他工具中的反编译代码来判断是否确实如此.
You might be able to tell if this is indeed the case by looking at the decompiled code in Reflector or some other tool.
这篇关于LINQ和正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!