[英]How can I simplify and Optimize this lambda expression?
我正在嘗試簡化和優化以下 lambda 表達式。 我的要求是獲得手機或電話 1 與 IntakePhoneNum 匹配的第一個潛在客戶。 我只想匹配前 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();
首先,我建議為屬性引入變量。 然后,不再區分 Length >= 10 和 Length < 10,而是簡單地使用 StartsWith。 最后,不要使用 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.