2009-11-17 34 views
0

如何在一個linq語句中執行此操作:如果獲取了我擁有的對象列表(id,name,parentId)。 現在我在這個列表中有3個層級。 我想要的是,當我在我的功能中獲得最高級別的Id時,我需要第三級別的Id。分層對象用linq檢索childsIds

我有本作的時刻:

Public List<int> GetIds(int objectId){ 
    var idList = new List<int>(); 
    //get the seconds level ids 
    var parentsIds = from n in myListObject 
        where n.parentId.equals(objectId) 
        select n.id; 
    //get the third level ids 
    foreach(var parentId in parentsIds){ 
    var childIds = from c in myListObject 
        where c.parentId.equals(parentId) 
        select c.id; 
    foreach(var childId in childIds){ 
     idList.Add(childId); 
    } 
    } 
    return idList; 
} 

所以我想知道如果我能做到這一點的一個LINQ聲明?

回答

1

我沒有測試過,但類似這樣的東西應該工作:

myListObject 
    .Where(child => 
    myListObject 
    .Where(obj => obj.parentId==objectId) 
    .Select(obj => obj.id) 
    .Contains(child.parentId)) 
    .Select(child => child.Id); 
+0

謝謝,我想它和它的工作 – Gerbrand 2009-11-17 12:10:42

+0

所以實際工作?驚人! :-) – Konamiman 2009-11-17 12:11:03