gpt4 book ai didi

c# - 如何在 LINQ-to-SQL 中模拟正则表达式

转载 作者:可可西里 更新时间:2023-11-01 08:19:22 31 4
gpt4 key购买 nike

我有一个包含客户帐号的数据库表。在同一个表中是与生产格式不匹配的测试帐户:例如,“A1111”是生产但“JTest”不是。我有 Regex,它只会提取我的生产帐户。我需要一个特定的编译查询来只提取生产账户。查询按地区和日期给我一个客户数量;和每个区域内的概念计数:

        getCustomerDistribution = CompiledQuery.Compile<DataContext, String, DateTime, IEnumerable<ServerLoad>>(
(context, region, processDate) => (from cust in context.GetTable<tbl_CustomerDistro>()
where cust.ProcessedDate.Date == processDate.Date
where cust.Region == region
where Regex.IsMatch(cust.AcctNum, ProductionMask)
group cust by new
{
cust.Region,
cust.Concept
} into custDistro
orderby custDistro.Key.Region
select new CustomerDistro
(
custDistro.Key.Region,
custDistro.Key.Concept,
custDistro
.Where(c => c.Concept == custDistro.Key.Concept)
.Select(c => c.Concept).Count()
)));

问题是我在运行时收到以下消息:

Method 'Boolean IsMatch(System.String, System.String)' has no supported translation to SQL.

我正在查看用户定义的函数:

static Func<striing, bool> IsProduction = (AcctNum) => Regex.IsMatch(AcctNum, ProductionMask);

这也行不通。我不想迭代检索到的记录以进一步过滤,除非没有其他方法可以做到这一点。

有没有办法用 Predicate Builder 做到这一点?

更新:

我认为的另一种选择是使用:

其中 SqlMethods.Like (cust.AcctNum, ProductionMask)

但是,我的 ProductionMask 是为 Regex 编写的:

^[B,G]\d{4}$

有没有办法用 SqlMethods.Like(...) 来做到这一点?

更新 2:

这是一个运行非常缓慢的查询。我有 3 个区域运行此查询,记录计数和返回时间为:
263: 903 毫秒
342: 822 毫秒
146: 711 毫秒

最佳答案

我更改了查询以使用以下内容代替 Regex.IsMatch:

where SqlMethods.Like(cust.Acct, ProductionMask)  

其中 ProductionMask = "[bBgG][0-9][0-9][0-9][0-9]"

等效的 RegEx 是:^[B,G]\d{4}$

如果有人发现 2 个掩码的结果不一样,请告诉我...

关于c# - 如何在 LINQ-to-SQL 中模拟正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5720987/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com