2016-09-06 68 views
0

比方说,我有这样的数据:如何在多个列表交换两个项目

列表:

  1. ListOfPoints =一
  2. ListOfPoints = B
  3. ListOfPoints = C
  4. ListOfPoints = d

现在我想要做的是:swap每个列表中有两个点(a,b,c,d),不幸的是它不起作用。

我尝试下面的代码:

List<List<Point3d>> currentGeneration = handoverPopulation.ToList(); 
foreach(List<Point3d> generation in currentGeneration) 
{ 
    int index1; 
    int index2; 
    Random r = new Random(); 
    index1 = r.Next(0, generation.Count); 
    index2 = r.Next(0, generation.Count); 

    if(index1 != index2) 
    { 
    Point3d cache = generation[index1]; 
    generation[index1] = generation[index2]; 
    generation[index2] = cache; 
    } 
} 

如何在多个列表同时交换两个点或为什么我的方法行不通?

这里是清单的图片之前和交换之后: enter image description here

感谢您的帮助。

+0

备注:对于本地变量,“generation”比'Var'更好。您可能想要阅读c#的命名约定。 – user3185569

+0

那是真的,我应该改变局部变量的名字。当我完成基本的程序时,我仍然会在最后改变一些东西。 – Meliss

+0

您的代码遇到了什么问题? – symmetricsaurus

回答

1

您不应为列表中的每个迭代创建新的Random实例。这样它就会重新进行迭代。由于种子是基于计时器的,因此每次可能会使用相同的值播种,因此会给出相同的值。

下面的代码为我工作:

Random r = new Random(); 
foreach (List<Point3d> generation in currentGeneration) 
{ 
    int index1; 
    int index2; 
    index1 = r.Next(0, generation.Count); 
    index2 = r.Next(0, generation.Count); 

    if (index1 != index2) 
    { 
     Point3d cache = generation[index1]; 
     generation[index1] = generation[index2]; 
     generation[index2] = cache; 
    } 
} 
+0

我要疯了,它仍然不适合我:/ – Meliss

+0

我还没有在Grasshopper中试过这个,只在C#控制台应用程序中。也许这个问题是在你的应用程序中的其他地方?你可以在你的代码中加入一个断点,看看它是否在运行?否则,试着找出你从Random.Next()得到的值。 – symmetricsaurus

+0

嘿,我现在知道了原因。它实际上正在工作,但代码将在两个列表中交换点。我有一个我用这个代码引用的初始列表,因此我不可能在交换之前和交换之后看到差异。为了改变这种情况,我唯一需要做的就是:首先克隆初始列表,以便比较它们! @symmetricsaurus – Meliss

1

它,当你尝试和周围交换点,是因为你在处理引用类型。创建'新'点(而不是引用现有点)解决了这个问题。在Grasshopper C#中测试。

int index1; 
int index2; 
Random r = new Random(); 
index1 = r.Next(0, generation.Count); 
index2 = r.Next(0, generation.Count); 

if(index1 != index2) 
{ 
    Point3d cache = new Point3d(generation[index1]); 
    generation[index1] = new Point3d(generation[index2]); 
    generation[index2] = cache; 
} 
+0

嘿@James R,谢谢。这也是一个好主意,但我只是克隆了列表,然后让交换代码运行。这是工作 :) – Meliss

0

感谢您的帮助。

我发现它为什么不起作用或为什么我没有看到任何区别。 这是因为有我想交换点的初始列表。为了达到这个目的,我只复制了洞列表,然后让交换代码运行。然而,这个程序会在这两个列表中进行交换,因此我不可能看到其中的差异。

毕竟麻烦了:)我唯一要做的就是克隆最初的列表。所以,我想这一点:

public static List<List<Point3d>> createGenerations(List<List<Point3d>> cGP, List<double> cGF, int genSize, Point3d startPoint) 
{ 
List<List<Point3d>> currentGeneration = new List<List<Point3d>>(cGP.Count); 
cGP.ForEach((item) => {currentGeneration.Add(new List<Point3d>(item));}); 
} 

现在我可以在“currentGeneration”掉任何我想要的,而之前和交换之后看到的差异。