2012-01-02 25 views
0

我有一個名爲Drinking的表。算法通過idParent屬性查找每個孩子

下面是它的外觀:

Name   idCategory idParentCategory 
drink   1    1 
alcohol   2    1 
nonalcohol  3    1 
tea    5    3 
juice   4    3 
sparkling  6    4 
nonsparkling  7    4 
pepsi   8    6 
schweppes  9    6 
wine   10    2 
beer   11    2 

現在,輸入idCategory。正如你可以看到沒有財產idChildren。我想要做的是找到孩子的ID。

例如,如果輸入爲1,則輸出應爲1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11

這裏是我的嘗試:

public void myMethod() 
{ 
    List<Drinking> drinkingList= (from d in myEntities.Drinking 
           select d).ToList(); 
    foreach (var d in drinkingList) 
    { 
     if (d.Drinking2Reference.EntityKey != null) 
     { 
      s = c.Drinking2Reference.EntityKey.EntityKeyValues[0].Value.ToString(); 
      idPD = Int32.Parse(s); 
      //get idParent 
      if (idPC == idCat) 
      { 
      //if idParent is equal as the input, put this idCategory 
      //in a list of integers. 
      //Now, here comes the tricky part. 
      //I should continue with this loop AND repeat this for 
      //every child of idPC. 
      //Where to put the call for this method? 
      //Where to put the return statement? 
      //Here is what I'm doing 
      myMethod(idPC); 
      } 
      else 
      { 
      myMethod(idPC); 
      } 
     } 

      } 
} 

我的目標是,以填補

+0

你的問題不清楚,所提供的代碼僅僅是一個框架..請更好地解釋你正在努力實現的目標。 – amit 2012-01-02 15:21:50

+0

@amit我的目標是用孩子的ID填寫一份清單。 – 2012-01-02 15:28:24

回答

1
public void myMethod(int value) 
{ 
    List<int> intList = new List<int>(); 
    List<Drinking> drinkingList= (from d in myEntities.Drinking 
          select d).ToList(); 
    foreach (var d in drinkingList) 
    { 
     if (d.Drinking2Reference.EntityKey != null) 
     { 
      if(d.idCategory == value) 
      intList.Add(value); 
      else { 
      for(int i=0; i < intList.Count; i++) { 
       if(intList.ElementAt(i) == d.idParentCategory) 
        intList.Add(d.idCategory); 
      } 
      } 

     } 
    } 
    //Print numbers  
} 

我沒有測試過這個孩子的識別碼與greatchildren名單,但我覺得它應該工作。隨時發表評論,如果你抓到了什麼。此外,該表必須按idParentCategory排序才能生效。我也會說,在這種情況下,我會建議你考慮使用樹木而不是桌子。

+0

它在foreach中崩潰,它說Collection被修改;枚舉操作可能不會執行。 – 2012-01-02 16:20:33

+0

如何處理崩潰? – 2012-01-02 16:29:25

+1

對不起,我忘了你不能更改使用該列表的foreach內的列表。我將foreach變成了循環的正常工作,現在應該可以工作。 – Mitch 2012-01-02 16:36:42