2012-08-13 51 views
2

假設我有這樣一些對象:更新列表的LINQ

Class NetworkSwitch 
{ 
    private String _name; 
    String name { get {return _name;} set {_name=value;}} 
    Dictionary<int, VLAN> VLANDict = new Dictionary<int, NetworkSwitch>(); 

public List<CiscoSwitch> GetAllNeigbors() 
     { 
      List<CiscoSwitch> templist = new List<CiscoSwitch>(); 

     foreach (KeyValuePair<int, CiscoVSAN> vlanpair in this.VLANDict) 
     { 

      templist.AddRange((vlanpair.Value.NeighborsList.Except(templist, new SwitchByNameComparer())).ToList()); 
     } 
     return templist; 
} 

Class VLAN 
{ 
    private Int _VLANNum; 
    Int VLANNum {get {return _VLANNum ;} set {_VLANNum =value;}} 

    //a neighbor is another switch this switch is connected to in this VLAN 
    // the neighbor may not have all same VLANs 
    List<NetworkSwitch> Neighbors = new List<NetworkSwitch>(); 
} 

以上就是這樣設計的,因爲兩個開關被物理連接可能不具有全部分配相同的VLAN。我試圖做的是逐步通過給定交換機上每個VLAN中的鄰居列表,並且如果名稱與輸入列表中的名稱匹配,則更新對其他交換機的引用。這是我試過的,它不會編譯。我想知道LINQ是否可以在某種程度上實現它,或者如果有更好的方法。

// intersect is the input list of NetworkSwitch objects 
//MyNetworkSwitch is a previously created switch 

foreach (NetworkSwitch ns in intersect) 
{ 
    foreach (KeyValuePair<int, VLAN> vlanpair in MyNetworSwitch.VLANDict) 
    { 
     foreach (CiscoSwitch neighbor in vlanpair.Value.Neighbors) 
     { // this is the line that fails - I can't update neighbor as it is part of the foreach 
      if (ns.name == neighbor.name) { neighbor = ns; } 
     } 
    } 
} 

另一個問題 - 我添加了獲取NetworkSwitch對象的所有鄰居的方法。假設我要獲取該列表,然後使用對具有相同名稱的交換機的不同實例的引用來更新它,是否會更新VLAN中NetworkSwitch對象的引用?

+0

你會意識到,定義你的屬性會產生一個計算器,由於無限的自我參照?如果你想創建對基礎字段存儲沒有特別要求的屬性,只需使用auto-properties:'int VLANNum {get;組; }' – mellamokb 2012-08-13 20:05:20

+0

修復了屬性。謝謝。 – 2012-08-13 20:08:21

回答

0

像這樣的東西應該工作:

 foreach (NetworkSwitch ns in intersect) 
     { 
      foreach (KeyValuePair<int, VLAN> vlanpair in ns.VLANDict) 
      { 
       if(vlanpair.Value.Neighbors.RemoveAll(n => n.name == ns.name) > 0) 
        vlanpair.Value.Neighbors.Add(ns); 
      } 
     } 
+0

中的數據的代碼謝謝。我會嘗試。我還在原始問題中增加了一些內容 – 2012-08-13 20:44:36

0

由於IEnumerable的工作原理,在迭代它的同時更改Enumerable的內容不是受支持的操作。

您將不得不使用更改後的值返回一個新列表,然後更新原始參考,或者使用純循環「ol」for (...; ...; ...)循環。

+0

我無法更新原始參考,還有其他屬性不應更改。我將不得不重新設計NetworkSwitch ojbect或更改解析輸入文件 – 2012-08-13 20:18:54