C# 将列表重置为新数量的对象
我在列表中积累了点3ds时遇到问题。当我通过grasshopper中的gui滑块更改int代理的数量时,数量会不断增加,而不是重置为新的数量。我猜我应该在某个地方重新初始化列表,或者在每次值更改时清除它?这样做的正确方法是什么C# 将列表重置为新数量的对象,c#,list,grasshopper,rhino3d,C#,List,Grasshopper,Rhino3d,我在列表中积累了点3ds时遇到问题。当我通过grasshopper中的gui滑块更改int代理的数量时,数量会不断增加,而不是重置为新的数量。我猜我应该在某个地方重新初始化列表,或者在每次值更改时清除它?这样做的正确方法是什么 protected override void SolveInstance(IGH_DataAccess DA) { BoundingBox box = new BoundingBox(0.0, 0.0, 0.0,
protected override void SolveInstance(IGH_DataAccess DA)
{
BoundingBox box = new BoundingBox(0.0, 0.0, 0.0, boundx, boundy, boundz);
DA.SetData("Bounding Box", box);
DA.SetData("Start", "The current trigger is set to " + started.ToString());
// Initialize Agents
for (int i = 0; i < agents; i++)
{
double xPos = RandomfromDouble(0.0, boundx);
double yPos = RandomfromDouble(0.0, boundy);
double zPos = RandomfromDouble(0.0, boundz);
Point3d pos = new Point3d(xPos, yPos, zPos); // Create Agent Start Position
Vector3d vec = new Vector3d(xPos + RandomfromDouble(-360.00, 360.00), yPos + RandomfromDouble(-360.00, 360.00), zPos + RandomfromDouble(-360.00, 360.00)); // Create Agent Start Vector
Agent agent = new Agent(pos, vec, alignment, separation, cohesion, neighborRadius);
allAgents.Add(agent);
DA.SetData("Debug", "# of Agents Created: " + allAgents.Count);
}
// Get agent positions
List<Point3d> agentPositions = new List<Point3d>();
List<Vector3d> agentVectors = new List<Vector3d>();
agentPositions = allAgents.Select(agent => agent.Pos).ToList();
agentVectors = allAgents.Select(agent => agent.Vec).ToList();
DA.SetData("Agent Count", allAgents.Count);
DA.SetDataList("Agent Points", agentPositions);
DA.SetDataList("Agent Vectors", agentVectors);
if (started)
{
DA.SetData("Start", "The current trigger is set to " + started.ToString());
for (int i = 0; i < generations; i++)
{
DA.SetData("Debug", "# of Generations: " + i);
foreach (Agent agent in allAgents)
{
DA.SetData("Debug", "# of Agents: " + i);
agent.UpdateAgent(allAgents);
}
}
}
else if (!started)
{
DA.SetData("Start", "The current trigger is set to " + started.ToString());
//return;
}
}
public double RandomfromDouble(double from, double to)
{
double diff = Math.Abs(from - to);
return rnd.NextDouble() * diff + from ;
}
如果我读对了你的代码,你的问题是allAgents列表越来越长。正如您所猜测的,这是因为您只在顶部创建了一次列表,然后只在for循环中添加它,该循环表示//初始化代理
如果您打算在此时重置列表,那么在进入for循环之前,我认为您需要执行allAgents.Clear。这将清空列表,然后您循环并在循环中添加新代理。谢谢,我已将我发布的代码编辑得更简洁。还刚刚意识到移动列表allAgents=新列表;返回SolveInstance函数,for循环也解决了这个问题。只要allAgents不需要从该方法外部引用,就可以将该行放入SolveInstance。如果确实如此,那么您需要在以前的位置创建列表,并在SolveInstance中清除它。