Search code examples
c#dynamics-crm

How can I simplify and Optimize this lambda expression?


I'm trying to simplify and optimize the following lambda expression. My requirement is to get the first lead whose mobile phone or telephone1 matches intakePhoneNum. I want to match first 10 digits only.

 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();

Solution

  • First, I would suggest to introduce variables for the attributes. Then, instead of the differentiation between Length >= 10 and Length < 10, simple use StartsWith. And last, instead of Where(...).FirstOrDefault, simply use 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;
     });