Skip to main content
 首页 » 编程设计

c#之在不考虑 Linq 中任何格式的情况下比较电话号码与实体并检查性能

2024年02月13日11youxin

我必须将 Linq 中的电话号码与实体进行比较。我正在使用正则表达式,这样我就可以只比较数字而忽略格式。

因为我们不能在 where 子句中使用正则表达式,所以我获取电话号码列表,然后应用循环来比较电话号码。

代码如下:

    /// <summary> 
    /// Check Phone number exist or Not 
    /// </summary> 
    /// <param name="accountNumber"></param> 
    /// <returns></returns> 
    public bool CheckPhoneNumberExist(string phoneNumber) 
    { 
        LP= new LPEntities(); 
 
        // In order to compare phone number, we need to use regex so that we can compare only numbers and not any specific format 
        phoneNumber = Regex.Replace(phoneNumber, "[^0-9]", ""); 
 
        var phoneList = (from act in LP.Accounts 
                         select act).ToList(); 
        if (phoneList.Count > 0) 
        { 
            foreach (var item in phoneList) 
            { 
                if (item.Telephone != null) 
                { 
                    if (Regex.Replace(item.Telephone, "[^0-9]", "") == phoneNumber) 
                    { 
                        return true; 
                    } 
                } 
            } 
        } 
 
        return false; 
      } 

代码运行良好,但存在性能问题。我们在数据库中有 20,000 条记录,这些记录还在不断增加,因此制作列表然后遍历该列表的速度很慢。

我们如何优化以上内容?是否有其他解决方案,比如我们是否可以使用存储过程来实现?

谢谢,

请您参考如下方法:

请注意,您的正则表达式技术不会识别出这些数字实际上是相同的:

+441234567890 
+44 (0)1234 567890 
01234 567890 

我的第一个选择是将数字存储为不带格式的 varchar,并且只对其进行格式化以供显示。这意味着您在检索时摆脱了正则表达式,您可以添加一个索引来进一步加快检索速度。

我的第二个选择是添加一个列,以便您存储两者并保持它们同步。

在这里查看答案:

Is it better to store telephone numbers in some canonical format or "as entered"?

最后,如果您将 linq 更改为此,您可能会得到一些改进:

bool exists = (from act in LP.Accounts 
               where act.Telephone != null //move the null check to the database 
               select act.Telephone)  //select only the telephone number 
              .AsEnumerable()  //using linq-to-objects 
                               //after retrieving the results from the database 
                               //lets you use Regex  
                               //- but it does get them all into memory 
              .Any(pn => Regex.Replace(pn, "[^0-9]", "") == phoneNumber)  
              //Any stops at the first one  
              //better than Counting them all then checking `> 0` 

顺便说一句。在foreach (var item in phoneList) 前面添加检查if (phoneList.Count > 0) 是多余的,因为如果没有则不执行循环体列表中的项目。