我们如何改进下面的代码行
本文关键字:代码 何改进 我们 | 更新日期: 2023-09-27 18:26:04
我们能改进这行代码吗
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;
}
一个简单的改进是取代
.Where( predicate ).Count() > 0
带有
.Any( predicate )
哦,如果这就是你的全部代码,你可以删除外部if,因为内部if条件和内部else-if条件都暗示了外部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;
如果 应用程序集合将始终只包含一个DeviceType(意味着同一集合中没有平板电脑和手机的混合),则上述内容可以缩短为:
l_Subscription.DeviceTypeID = l_Subscription.PackageInfo.Applications.First(x => x.DeviceType == DeviceType.Tablet || x.DeviceType == DeviceType.Phone);
当然,只有你知道这是否是你的场景的合理假设。。。