2010-06-11 25 views
0

我有一段代碼與結果集稱爲「結果」(原來我知道),但取決於傳入的變量我想要觸發特定查詢依賴。我有一個if語句中的下面,但這只是讓「結果」記錄集得到那些討厭的紅線,它不起作用。我相信這很容易解決。結果集使用兩個不同的視圖(從一個if語句)

if (area == "dashboard") 
    { 
     IQueryable<ViewGetNavigationMainItem> result = (from m in 
      _entities.ViewGetNavigationMainItems 
      where m.area.Trim() == area.Trim() 
      where m.state == "Online" 
      where m.parentID == parentID 
      orderby m.sequence ascending 
      select m);    
    } 
else 
    { 
     //Get the Content Items 
     IQueryable<ViewGetNavigationContentItem> result = (from m in 
      _entities.ViewGetNavigationContentItems 
      where m.navID == navID 
      where m.parentID == parentID 
      orderby m.contentOrder ascending 
      select m); 
    } 
maxRecords = result.Count(); 

foreach (var item in result) 
{ 
    //do something 
} 
+0

你的問題到底是什麼? – 2010-06-11 11:23:08

回答

1

注意:您可以使用&&而不是多個where

首先,if之前定義result作爲一個IQueryable基類或接口兩種類型的結果的(在C#4.0)或作爲Enumerable。你可以創建這樣一個基類。比方說,爲ViewGetNavigationMainItemViewGetNavigationContentItem唯一的公共基類是Object

IQueryable<object> result; 

if (area == "dashboard") 
         { 
          result = (from m in _entities.ViewGetNavigationMainItems 
             where m.area.Trim() == area.Trim() 
             && m.state == "Online" 
             && m.parentID == parentID 
             orderby m.sequence ascending 
             select m); 
         } 
         else 
         { 
          //Get the Content Items 
          result = (from m in _entities.ViewGetNavigationContentItems 
             where m.navID == navID 
             && m.parentID == parentID 
             orderby m.contentOrder ascending 
             select m); 
         } 

foreach,而不是var使用基類(或通用接口)兩種ViewGetNavigationMainItemViewGetNavigationContentItem。如果您沒有比Object更具體的基類,請使用object

foreach (object item in result) 
         { etc etc etc 
1
在你的代碼

,「結果」不在範圍內,當您檢查,因爲它是在「如果」聲明的數量和「其他」

你需要移動的結果上面的聲明如果,並將它聲明爲兩個結果,例如IEnumerable。

,如果你想要做的是算來那是......如果你想要做更多,考慮創建一個模型,你可以選擇這兩個成果轉化,例如

class ResultModel{ 
int Id{get;set;} 
string Display{get;set;} 
}