假設我有這樣一些對象:更新列表的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對象的引用?
你會意識到,定義你的屬性會產生一個計算器,由於無限的自我參照?如果你想創建對基礎字段存儲沒有特別要求的屬性,只需使用auto-properties:'int VLANNum {get;組; }' – mellamokb 2012-08-13 20:05:20
修復了屬性。謝謝。 – 2012-08-13 20:08:21