我把下面的代码拼凑在一起,从我的用户配置文件数据中获取一些细节它很管用,但不好看
我有一个保存在用户配置文件中的UserPreferences
对象。它具有是否需要SMS警报消息以及警报类型的属性。短信将以电子邮件形式发送。当创建警报时,我希望获得一个逗号分隔的地址字符串,该字符串应该得到该警报类型的通知。
用户有一个手机号码和一个运营商。运营商有一种类似"{number}@ {domain}
的短信电子邮件格式,我将用用户号码和运营商的域替换这些字段。
正如我所说,这确实有效,但我不在乎它是两种方法,也不在乎它看起来有多混乱有没有一种更紧凑的方法将其作为一种方法来编写
public static string GetSMSAlertSubscribers(int alertTypeId) {
// end result I want is like: "1234567890@vtext.com,0987654321@text.att.net"
return String.Join(",", GetSMSAlertSubscribersEnumerable(alertTypeId));
}
public static IEnumerable<string> GetSMSAlertSubscribersEnumerable(int alertTypeId) {
var prefs = Membership.GetAllUsers()
.Cast<MembershipUser>()
.Where(u => WebProfile.GetProfile(u.UserName).Preferences.SendAlertsToSMS.Equals(true)
&& WebProfile.GetProfile(u.UserName).Preferences.SMSAlertTypeIds.Contains(alertTypeId))
.Select(u => WebProfile.GetProfile(u.UserName).Preferences);
var carriers = new AlertRepository().FindAllMobileCarriers().ToList();
foreach (UserPreferences p in prefs) {
yield return carriers.Where(c => c.Id.Equals(p.MobileCarrierId))
.Select(c => c.SMSEmailAddressFormat.Replace("{domain}", c.SMSEmailAddressDomain).Replace("{number}", p.MobileNumber))
.SingleOrDefault();
}
}
我会这样称呼它:
var emailTo = GetSMSAlertSubscribers(3);
更新:我已经重构了我的"prefs"查询,以减少GetProfile()
作为的重复使用
var prefs = Membership.GetAllUsers()
.OfType<MembershipUser>()
.Select(u => WebProfile.GetProfile(u.UserName).Preferences)
.Where(p => p.SendAlertsToSMS && p.SMSAlertTypeIds.Contains(alertTypeId));
var q = from x in
(from p in prefs
from c in carriers
where p.MobileCarrierId == c.Id
select new
{
c.SMSEmailAddressFormat,
c.SMSEmailAddressDomain,
p.MobileNumber
}).Distinct()
select x.SMSEmailAddressFormat
.Replace("{domain}", x.SMSEmailAddressDomain)
.Replace("{number}", x.MobileNumber);
return String.Join(", ", q);
var q = from p in prefs
from c in carriers
where p.MobileCarrierId == c.Id
select c.SMSEmailAddressFormat
.Replace("{domain}", c.SMSEmailAddressDomain)
.Replace("{number}", p.MobileNumber);
return String.Join(", ", q.Distinct());
Mh,这个怎么样:
var prefs = Membership
.GetAllUsers()
.OfType<MembershipUser>()
.Select(u => WebProfile.GetProfile(u.UserName).Preferences)
.Where(p => SendAlertToSMS.Equals(true) && SMSAlertTypeIds.Contains(alertTypeId));
var carriers = new AlertRepository().FindAllMobileCarriers().ToList();
foreach (UserPreferences p in prefs)
{
var carrier = carriers.FindOrDefault(c => c.Id.Equals(p.MobileCarrierId));
yield return PopulateAddress(c, p);
}
并在PopulateAddress
中进行替换。现在看起来不那么乱了。把所有东西都塞进一个Linq查询中并不一定是最好的做法。