gpt4 book ai didi

c# - 使用 Linq 更新列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:27:56 24 4
gpt4 key购买 nike

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

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

最佳答案

像这样的东西应该可以工作:

        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);
}
}

关于c# - 使用 Linq 更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11941428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com