首页 > 解决方案 > 在 C# 中使用 SqlFunctions 修剪字符

问题描述

这是我的代码:

(from customer in db.tblCustomers
  join product in db.tblProducts on customer.product_id equals product.id into str
  from prod in str.DefaultIfEmpty()
  where customer.code.Substring(SqlFunctions.PatIndex("%[^0]%", customer.code).Value - 1) == customerCode
  select prod.name).SingleOrDefault();

如您所见,我使用 PatIndex 左修剪字符串,但我也想右修剪零。我怎样才能做到这一点?

例如,如果 customerCode 是“123”,并且在 db 中,如果我有一个值为“001230000”的客户代码,则匹配。

标签: c#entity-frameworklinqtsql

解决方案


验证CustomerCode全为零后的字符:

(from customer in db.tblCustomers
  join product in db.tblProducts on customer.product_id equals product.id into str
  from prod in str.DefaultIfEmpty()
  let tail = customer.code.Substring(customer.code.IndexOf(customerCode)+customerCode.Length)
  where customer.code.Substring(SqlFunctions.PatIndex("%[^0]%", customer.code).Value - 1) == customerCode &&
        tail == new String('0', tail.Length)
  select prod.name).SingleOrDefault();

推荐阅读