2012-02-29 47 views
2

我們可以改善這行代碼我們如何改進下面的代碼行?

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

我計數8行,而不是一個。你想要「改進」什麼? – Oded 2012-02-29 11:24:15

+0

任何更好的方法來重新編寫陳述 – user1025901 2012-02-29 11:33:20

回答

6

一個簡單的改進是更換

.Where(predicate).Count() > 0 

.Any(predicate) 

哦,如果這是所有的代碼,你可以刪除外,如果,因爲無論是內如果條件和內部否則,如果條件暗示外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; 
+0

我剛剛更新了這個問題,我剛剛嘗試過,但沒有正常工作......需要幫助......將不勝感激,如果你能幫助我 – user1025901 2012-02-29 11:56:30

0

IF應用程序集合將永遠只包含一個單一的設備類型(即沒有同一個集合在兩個平板電腦和手機的混合),那麼上面可以簡化爲:

l_Subscription.DeviceTypeID = l_Subscription.PackageInfo.Applications.First(x => x.DeviceType == DeviceType.Tablet || x.DeviceType == DeviceType.Phone); 

當然只有你知道這是否是一個y的合理假設我們的場景...