Regex 不适用于 Linq to Sql

本文关键字:to Sql Linq 适用于 不适用 Regex | 更新日期: 2023-09-27 18:36:33

我有以下代码

Regex R = new Regex("my regex");
var q = from c in db.tble1
        where R.IsMatch(c.text)
        select c;

在调试时,我在 Q 结果中看到此消息

方法'Boolean IsMatch(System.String)'不支持转换为SQL。 System.SystemException {System.NotSupportedException}

那我做错了什么?

编辑:I了解到该方法不支持转换为 SQL
但是如何解决这个问题

Regex 不适用于 Linq to Sql

Regex 不支持转换为 SQL。错误说明了一切。不能在 LINQ to SQL 中使用正则表达式。

尝试改用likesubstring比较:

var q = from c in db.tble1
        where c.text.StartsWith("x") && c.text.Substring(2, 1) == "y"
        select c;

或者,您可以执行内存中的正则表达式比较。您可以通过在使用Regex之前调用ToList()来执行此操作:

Regex R = new Regex("my regex");
var q = from c in db.tble1.ToList()
        where R.IsMatch(c.text)
        select c;