我正在尝试简化和优化以下lambda表达式。我的要求是获得第一条手机或电话号码与摄入电话号码匹配的线索。我只想匹配前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();
答案 0 :(得分:2)
首先,我建议为属性引入变量。 然后,代替使用“长度> = 10”和“长度<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;
});