2011-07-14 62 views
1

我有類如下:集團項目爲母公司 - >兒童 - >大的親子關係

public class Item 
    { 
     public int ItemID { get; set; } 
     public int GroupLevel { get; set; } 
     public string ItemName { get; set; } 
     public string ItemDesc { get; set; } 
    } 

這回的扁平化IEnumerable的結果,但我需要將它們分組到一個父 - >子 - > Grand-child關係,基於GroupLevel和ItemID。下面是目前的數據看怎麼樣:

ItemID:  1 
GroupLevel: 1 
ItemName: All Groups 
ItemDesc: Item 1 description 
ParentID: null 

ItemID:  2 
GroupLevel: 2 
ItemName: Boulder 
ItemDesc: Boulder description 
ParentID: 1 

ItemID:  3 
GroupLevel: 2 
ItemName: Atlanta 
ItemDesc: Atlanta description 
ParentID: 1 

ItemID:  4 
GroupLevel: 3 
ItemName: Boulder - Boulder south 
ItemDesc: Grand-child of Boulder (ID: 2) 
ParentID: 2 

ItemID:  5 
GroupLevel: 3 
ItemName: Boulder - Boulder North 
ItemDesc: Another grand-child of Boulder (ID: 2) 
ParentID: 2 

ItemID:  6 
GroupLevel: 3 
ItemName: Atlanta - West 
ItemDesc: Grand-child of Atlanta (ID: 3) 
ParentID: 3 

我想有結構化的這樣的數據:

ItemID:  1 
GroupLevel: 1 
ItemName: All Groups 
ItemDesc: Item 1 description 
ParentID:  null 

    ItemID:  2 
    GroupLevel: 2 
    ItemName: Boulder 
    ItemDesc: Boulder description 
    ParentID:  1 

     ItemID:  4 
     GroupLevel: 3 
     ItemName: Boulder - Boulder south 
     ItemDesc: Grand-child of Boulder (ID: 2) 
     ParentID:  2 

     ItemID:  5 
     GroupLevel: 3 
     ItemName: Boulder - Boulder North 
     ItemDesc: Another grand-child of Boulder (ID: 2) 
     ParentID:  2 


    ItemID:  3 
    GroupLevel: 2 
    ItemName: Atlanta 
    ItemDesc: Atlanta description 
    ParentID:  1 

     ItemID:  6 
     GroupLevel: 3 
     ItemName: Atlanta - West 
     ItemDesc: Grand-child of Atlanta (ID: 3) 
     ParentID:  3 

什麼建議嗎?謝謝。

回答

1

你的意思是這樣的:

List<Item> itemlist; 
    List<Item> newItemList; 

    public void main() 
    { 
     //Find all root items (aka, no parents) 
     foreach (Item item in itemlist) 
     { 
      if (item.Parent == null) getObjects(item.ID, 0); 
     } 
    } 

    public void getObjects(Item me, int deep) 
    { 
     //Store node 
     Console.WriteLine("this is me: " + me.ID); 
     Console.WriteLine("I am this many levels deep: " + deep); 
     newItemList.Insert(me); 

     //Find my children 
     foreach (Item item in itemlist) 
     { 
      if (item.Parent == me.ID) getObjects(item.ID, (deep + 1)); 
     } 
    }