2013-02-07 22 views
3

我有3種類型的對象,TypeA,TypeB,TypeC。類型A具有類型B的列表和類型B具有TypeC的列表,並TypeC有一些變量,我想跟蹤Linq:有沒有辦法搜索符合條件的值的對象列表列表?

Class TypeA 
{ 
    List<TypeB> MyListOfTypeB; 
    //... 
} 

Class TypeB 
{ 
    List<TypeC> MyListOfTypeC; 
    //... 
} 

Class TypeC 
{ 
    int SomeInteger; 
    //... 
}   

給定一個List<TypeA> MyListOfTypeA,我想看看所有TypeC對象,其滿足一定的條件,如,SomeInteger> 100.除了/ foreach循環的嵌套外,Linq的方式是什麼?

回答

3
var MyListOfTypeA = new List<TypeA>(); 
// ... 
var cItems = 
    from a in MyListOfTypeA 
    from b in a.MyListOfTypeB 
    from c in a.MyListOfTypeC 
    where c.SomeInteger > 100 
    select c; 

以上是等效於調用SelectMany LINQ功能,但在我看來,這是顯著更清潔和更容易閱讀。

與LINQ功能做這(如已經由梅德建議,但有一些修改):

var cItems = 
    MyListOfTypeA.SelectMany(a => a.MyListOfTypeB) 
       .SelectMany(b => b.MyListOfTypeC) 
       .Where(c => c.SomeValue > 200); 
+1

是的,這是等價的,但在我的經驗,當查詢變得越來越複雜,很容易在LINQ的的extention方法使用Lambda表達式時,我清楚地看到每個語句的範圍。但我只能將此作爲個人意見和偏好提供。此外,查詢語法後來被轉換成我在編譯過程中使用的擴展方法,我相信,我喜歡處理被調用的實際方法,而不是使用簡化的語法糖抽象,有時令人困惑,因爲它看起來像SQL,但是不是。對不起,咆哮。 –

+0

@Dmitry - 我完全同意。如果查詢更復雜,我可能會將其重寫爲一系列LINQ函數。我在特定情況下使用更清晰的東西。 – JDB

2

你可以使用LINQ做下列方式:

var myListOfTypeA = new List<TypeA>(); 

    // fill your list here 

    var typeCs = from typeA in myListOfTypeA 
       from typeB in typeA.MyListOfTypeB 
       from typeC in typeB.MyListOfTypeC 
       where typeC.SomeInteger > 100 
       select typeC; 
+0

但在原始情況下,MyListOfTypeA沒有TypeC的任何對象。它只包含A類型的對象,每個對象都有一個「B」列表,每個列表都有一個「C」列表。 –

+0

@JenS oops,...更新了我的答案 – Beachwalker

4

像這樣的事情是你在找什麼我認爲:

var result = MyListOfTypeA.SelectMany(b => b.MyListOfTypeB.SelectMany(c => c.MyListOfTypeC.Select(x => x.SomeInteger > 100))).ToList(); 
+0

其實,我相信這將是一個普通的'Select()'前兩種類型。 – IronMan84

+0

我不知道,但我認爲它會更像這樣:'var result = MyListOfTypeA.SelectMany(b => b.MyListOfTypeB).SelectMany(c => c.MyListOfTypeC).Select(x => x.SomeInteger > 100).ToList();' 但我現在無法測試。 – Johnny5

+0

也就是說,@ Cyborgx37提出的linq語法在這種情況下看起來更乾淨...... – Johnny5

1

你需要導航所有的子列表,什麼from可以爲你做。

var ta = new TypeA(); 

var allTypeCsThatSatisfyMyCondition = 
    from tb in ta.MyListOfTypeB      // This will iterate to each item in the list 
    from tc in tb.MyListOfTypeC      // This will iterate to each item in the *sublist* 
    where tc.SomeInteger > 100   // Condition could be anything; filter the results 
    select tc;          // When you select, you tell your iterator to yield return that value to the caller. 

return allTypeCsThatSatisfyMyCondition.ToList(); // To list will force the LINQ to execute and iterate over all items in the lists, and add then to a list, effectively converting the returned items to a list. 
相關問題