简体   繁体   English

如何简化和优化此 lambda 表达式?

[英]How can I simplify and Optimize this lambda expression?

I'm trying to simplify and optimize the following lambda expression.我正在尝试简化和优化以下 lambda 表达式。 My requirement is to get the first lead whose mobile phone or telephone1 matches intakePhoneNum.我的要求是获得手机或电话 1 与 IntakePhoneNum 匹配的第一个潜在客户。 I want to match first 10 digits only.我只想匹配前 10 位数字。

 Entity matchingLead = 
     allLeads.Where(l => 
         (l.Attributes.Contains("mobilephone") && 
         (Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "").Length >=10 
             ? Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "").Substring(0,9) 
             : Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "").Substring(0)).Equals(intakePhoneNum))||
         (l.Attributes.Contains("address1_telephone1") && 
         (Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "").Length >= 10 
             ? Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "").Substring(0, 9) 
             : Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "").Substring(0)).Equals(intakePhoneNum))).FirstOrDefault();

First, I would suggest to introduce variables for the attributes.首先,我建议为属性引入变量。 Then, instead of the differentiation between Length >= 10 and Length < 10, simple use StartsWith.然后,不再区分 Length >= 10 和 Length < 10,而是简单地使用 StartsWith。 And last, instead of Where(...).FirstOrDefault, simply use FirstOrDefault(...)最后,不要使用 Where(...).FirstOrDefault,只需使用 FirstOrDefault(...)

Entity matchingLead = 
 allLeads.FirstOrDefault(l => 
 {
    if (l.Attributes.Contains("mobilephone"))
    {
        var phone = Regex.Replace(l.Attributes["mobilephone"].ToString(), "[^0-9]", "");
        if (phone.StartsWith(intakePhoneNum))
            return true;
    }
    if (l.Attributes.Contains("address1_telephone1"))
    {
        var phone = Regex.Replace(l.Attributes["address1_telephone1"].ToString(), "[^0-9]", "");
        if (phone.StartsWith(intakePhoneNum))
            return true;
    }
    return false;
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM