使用Linq更新列表

时间:2012-08-13 20:02:48

标签: c#

假设我有一些像这样的对象:

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对象的引用?

2 个答案:

答案 0 :(得分:0)

由于IEnumerable的工作原理,在迭代它时更改Enumerable的内容不是受支持的操作。

您必须返回包含更改值的新列表,然后更新原始引用,或使用普通的“for (...; ...; ...)循环。

答案 1 :(得分: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);
            } 
        }