2012-08-13 43 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