我们可以改进这行代码
if ((l_Subscription.PackageInfo.Applications.Where(x => x.DeviceType != DeviceType.UnKnown)).Count() > 0)
{
//l_Subscription.DeviceTypeID = ((l_Subscription.PackageInfo.Applications.Where(x => x.DeviceType == DeviceType.Tablet)).Count() > 0)?()
if ((l_Subscription.PackageInfo.Applications.Where(x => x.DeviceType == DeviceType.Tablet)).Count() > 0)
l_Subscription.DeviceTypeID = (int)DeviceType.Tablet;
else if ((l_Subscription.PackageInfo.Applications.Where(x => x.DeviceType == DeviceType.Phone)).Count() > 0)
l_Subscription.DeviceTypeID = (int)DeviceType.Phone;
}
我刚试过以下但没有工作......需要帮助
int cnt = DoOperation(l_Subscription.PackageInfo.Applications, x => x.DeviceType != DeviceType.UnKnown);
if(cnt > 0)
{
int cnt1 = DoOperation(l_Subscription.PackageInfo.Applications, x => x.DeviceType == DeviceType.Tablet);
int cnt2 = DoOperation(l_Subscription.PackageInfo.Applications, x => x.DeviceType == DeviceType.Phone);
if(cnt1 > 0) l_Subscription.DeviceTypeID = (int)DeviceType.Tablet;
else if (cnt2 > 0) l_Subscription.DeviceTypeID = (int)DeviceType.Phone;
}
private int DoOperation<TKey>(List<l_Subscription.PackageInfo.Applications> list, Func<l_Subscription.PackageInfo.Applications, TKey> predicate)
{
int count = 0;
count = list.Where(predicate).Count();
return count;
}
答案 0 :(得分:6)
一个简单的改进就是替换
.Where( predicate ).Count() > 0
与
.Any( predicate )
哦,如果那是你的所有代码,你可以删除外部if,因为内部if条件和内部else条件都暗示外部if条件,给你:
if ((l_Subscription.PackageInfo.Applications.Any(x => x.DeviceType == DeviceType.Tablet))
l_Subscription.DeviceTypeID = (int)DeviceType.Tablet;
else if ((l_Subscription.PackageInfo.Applications.Any(x => x.DeviceType == DeviceType.Phone))
l_Subscription.DeviceTypeID = (int)DeviceType.Phone;
答案 1 :(得分:0)
IF Application集合将始终只包含一个DeviceType(意味着同一集合中没有Tablets和Phones的混合),然后可以将上述内容缩短为:
l_Subscription.DeviceTypeID = l_Subscription.PackageInfo.Applications.First(x => x.DeviceType == DeviceType.Tablet || x.DeviceType == DeviceType.Phone);
当然只有你知道这对你的场景是否是一个合理的假设......