2010-11-01 46 views
4

這可能看起來很複雜,但我實際上只是試圖從A中選擇所有記錄及其子項,其中子項中存在特定條件。尋找語法,我可以添加到一個變量,讓我來過濾一堆條件Linq:在嵌套模型上執行Where()子句

如果你有這樣一個嵌套的視圖(如規範模式):

var a = from Arow in Atable 
     where ??? 
     select new AViewModel {     // (image Products) 
      id = Arow.id, 
      name = Arow.Name, 
      Brows = (from Brow in Arow.Brows 
        select new BViewModel {  // (sold in different regions) 
         id = Brow.id, 
         name = Brow.Name, 
         Crows = (from Crow in Brow.Crows 
            select new CViewModel { // (and in many stores) 
             id = Crow.id, 
             name = Crow.Name 
            } 
        } 
     }; 

和文字較從網頁上查詢,像這樣的(規範模式?) 我們使用jQuery選擇的運營商

filter[] = { "Brow.Name = Joe", "Crow.Name = Kim" } 

你怎麼能過濾用這些標準的表達A(像^ =表示「開頭」)?換句話說,你可以有一個where表達式,像a.Where()可以過濾嵌套屬性?

我可憐的嘗試:

var b = from row in a 
     where a.Brow.Where(b => b.name == "Joe") && 
       a.Brow.Crow.Where(c => c.name == "Kim") 
     select row; 

我真正需要的是這樣的:

Select * 
from A join B on A.key = B.key join C on B.key = C.key -- propagated keys 
where exists (select null from B where A.key = B.key and B.Name = "Joe") and 
     exists (select null from C where A.key = C.key and C.Name = "Kim") 

特別是,如果我能做到這一點:

var result = a.Where(first).Where(second); 

回答

7

你的「窮人的嘗試「並不遙遠。剛剛替補Any()Where()

var b = from row in a 
     where a.Brow.Any(b => b.name == "Joe") && 
       a.Brow.Crow.Any(c => c.name == "Kim") 
     select row; 

編輯補充:

你可能想要做一個區分大小寫的比較,但是,例如,.Any(b => b.name.Equals("Joe", StringComparison.CurrentCultureIgnoreCase))

+0

這幾乎是正確的,還是我做錯了什麼。 a.Brow.Any()可以工作,但使用a.Brow.Crow到達Crow會失敗。然而,a.Brow.Any(p => p.Crow.Any(c => c.name ==「Kim」))看起來很有希望。 – 2010-11-04 21:25:07

2

或者爲了好玩,你可以做的拉姆達equivilant:

var b = a.where(x => x.Brow.Any(b => b.name == "Joe") 
        && x.Brow.Crow.Any(c => c.name == "Kim") 
     .Select(y => y.row);