【问题标题】:how to swap two items in multiple lists如何交换多个列表中的两个项目
【发布时间】:2016-09-06 12:07:54
【问题描述】:

假设我有这个数据:

列表:

  1. ListOfPoints = 一个
  2. ListOfPoints = b
  3. ListOfPoints = c
  4. ListOfPoints = d

现在我要做的是:在每个列表中交换两个点(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;
  }
}

如何同时交换多个列表中的两个点,或者为什么我的方法不起作用?

这是列表交换前后的图片:

感谢您的帮助。

【问题讨论】:

  • 旁注:对于局部变量,generationVar 更好。您可能需要阅读 c# 的命名约定。
  • 没错,我应该更改局部变量的名称。当我完成基础程序后,我仍然会在最后更改一些内容。
  • 您的代码遇到了什么问题?
  • 我不知道为什么,但是这段代码没有交换任何列表(a、b、c、d)中的任何点。交换前后的列表仍然相同。让我发一张图片。 @对称龙

标签: c# list swap grasshopper


【解决方案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;
    }
}

【讨论】:

  • 我没有在 Grasshopper 中尝试过,只在 C# 控制台应用程序中尝试过。也许问题出在您的应用程序的其他地方?你能在你的代码中放一个断点,看看它是否运行?否则,请尝试找出您从 Random.Next() 获得的值。
  • 嘿,我现在找到了原因。它实际上正在工作,但代码会在两个列表中交换点。我有一个使用此代码引用的初始列表,因此我无法看到交换之前和交换之后的差异。要改变这一点,我唯一要做的就是:首先克隆初始列表,以便您可以比较它们! @对称龙
【解决方案2】:

这是因为当您尝试交换点时,您正在处理引用类型。创建“新”点(而不是引用现有点)解决了这个问题。在 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;
}

【讨论】:

  • 嘿@James R,谢谢。这也是一个好主意,但我只是克隆了列表,然后让交换代码运行。它正在工作:)
【解决方案3】:

感谢您的帮助。

我发现它为什么不起作用或为什么我看不到任何区别。 这是因为有我想交换积分的初始列表。为此,我只是复制了孔列表,并让交换代码运行。但是,该程序会在两个列表中交换,因此我无法看到差异。

毕竟麻烦 :) 我唯一要做的就是克隆初始列表。所以我尝试了这个:

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”中交换我想要的任何东西,同时查看交换前后的差异。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 2011-12-15
    • 2012-12-10
    • 2011-01-06
    • 2012-04-23
    • 1970-01-01
    • 2012-12-15
    • 2022-06-17
    相关资源
    最近更新 更多