2011-12-12 37 views
0

我在ObservableCollection中有一個項目的單子列表。這些項目具有屬性item.Id和item.Parent.Id。 我已經得到父(頂級)的ID,現在用這個ID我需要遍歷列表,並找到這個父母的孩子。每個孩子只能有一個父母,父母可以有多個孩子。從單位名單中獲取子女

我該如何有效地做到這一點?

回答

1

您可以使用:

var childrenOfParent = theCollection.Where(item => item.Parent.Id == parentId); 

編輯迴應評論:

假設你有一個分層數據集,我會親自做檢查,看看是否給定項目的程序有一個特定的項目作爲父遞歸,如下所示:

bool HasParent(Item item, int parentId) 
{ 
    if (item.Parent == null) 
     return false; 
    else if (item.Parent.Id == parentId) 
     return true; 
    else 
     return HasParent(item.Parent, parentId); 
} 

鑑於此,您可以使用:

var childrenOfParent = theCollection.Where(item => HasParnet(item, parentId)); 
+0

對不起,忘了把這個放在我的描述中,但事情是,父母的孩子也可以包含他們自己的孩子等等。 – tutu

+0

這只是讓孩子在一個級別。孩子可以包含他們自己的孩子等,這段代碼不會得到它們。至少我認爲它沒有或者我做錯了什麼? – tutu

+0

@tutu編輯顯示一種方法來處理此... –

0

嗯,我知道了,但是,如果任何人都可以優化/重構這個代碼轉換成一些更有效的,請讓我知道,我會標記爲一個答案,你的反應。只要我學習:)。

 foreach (var item in myitemlist) // first put the top level parent in the queue 
     { 
      if (parentitem.Id == item.Id) 
      { 
       filteredChildrenQueue.Enqueue(item); 
      } 
     } 

     while (!stillsearching) 
     { 
      if (filteredChildrenQueue.Count == 0) 
      { 
       stillsearching = true; 

       return; 
      } 

      FindParentChild(); 
     } 

保持調用此方法和處理隊列中的

private void FindParentChild() 
    { 
     foreach (var item in myitemlist) 
     { 
      if (item.Parent.Id == filteredChildrenQueue.ElementAt(0).Id) 
      { 
       filteredChildrenQueue.Enqueue(item); 
      } 
     } 

     filteredChildrenList.Add(filteredChildrenQueue.ElementAt(0)); 
     filteredChildrenQueue.Dequeue(); 
    } 

filteredChildrenList將包含頂層父+它包含了所有孩子的第一個項目。