C# 通过嵌套列表使用foreach循环,并对列表中的每个对象执行函数
我有两节课。一个称为组件,第二个称为管道C# 通过嵌套列表使用foreach循环,并对列表中的每个对象执行函数,c#,foreach,C#,Foreach,我有两节课。一个称为组件,第二个称为管道 *Component Class* string id; int flow; List<PipeLine> ConnectedPipeLines; void ChangeFlow(int flow); void CalculateFlow(); *PipeLine Class* int flow; Component startComponent; Component end
*Component Class*
string id;
int flow;
List<PipeLine> ConnectedPipeLines;
void ChangeFlow(int flow);
void CalculateFlow();
*PipeLine Class*
int flow;
Component startComponent;
Component endComponent;
void RecalculateFlow();
创建管道后,管道将添加到开始和结束组件的ConnectedPipeline列表中
所以ConnectedPipeLines.Add(p)代码>被执行
我有一个函数可以更改任何组件的流,我希望遍历每个组件并执行component.CalculateFlow(),然后我可以执行pipeline.CalculateFlow()来重新计算管道的流,因为endComponent从管道流获取其流
我就是这样做的,但是如果我调试它以找出我正在循环的当前管道中连接的两个组件,它只会重新计算第一级(组件A1和AB),而不会重新计算组件A10和组件A11。我哪里做错了
foreach(var pipe in pump.Output.StartComponent.ConnectedPipeLines) {
pipe.EndComponent.CalculateFlow();
foreach(var p in pipe.EndComponent.ConnectedPipeLines) {
p.EndComponent.CalculateFlow();
foreach(var item in p.EndComponent.ConnectedPipeLines) {
item.EndComponent.CalculateFlow()
}
}
}
你可以沿着水流递归下降。大概是这样的:
calculateDownstreamFlow(pump.Output.StartComponent.ConnectedPipeLines);
function void calculateDownstreamFlow(List<Pipeline> pipes) {
foreach(var pipe in pipes) {
pipe.EndComponent.CalculateFlow();
calculateDownstreamFlow(pipe.EndComponent.ConnectedPipeLines);
}
}
计算的下游流量(泵、输出、启动组件、连接管道);
函数void CalculatedDownstreamflow(列出管道){
foreach(管道中的var管道){
管道.EndComponent.CalculateFlow();
计算下游流量(管道.末端组件.连接管道);
}
}
Hmmm很难在短时间内重新创建整个流程,但首先想到的是:你应该在这里使用递归,不清楚你想在这里实现什么。正在试图根据A10和A1之间的流量等计算出有多少流量流向组件A?或者你是在试图根据A的输出量来计算A10、A11等的流量?每个组件都在添加来自其他组件的流之外吗?组件没有StartComponent变量,管道有。它是pipe.StartComponent.ConnectedPipeLines
。谢谢你的帮助。
calculateDownstreamFlow(pump.Output.StartComponent.ConnectedPipeLines);
function void calculateDownstreamFlow(List<Pipeline> pipes) {
foreach(var pipe in pipes) {
pipe.EndComponent.CalculateFlow();
calculateDownstreamFlow(pipe.EndComponent.ConnectedPipeLines);
}
}