首页 > 解决方案 > C# linq 数组到字典,各自的索引作为值中的列表/数组

问题描述

我正在尝试为我的用例找出最佳方法。我想要的是一个字典,其中 Vector3 作为键和这些vector3数组中的相应索引。

所以给定: Vertex[] vertices <- 每个顶点都包含位置(vector3)并且在数组中按顺序排列(在给定的索引处很重要)

该数组中的某些索引(顶点)可以共享相同的位置,我想按该位置对它们进行分组,并使用它们在数组中的相应索引。

public class MyClass {
  public Vector3 position;

  public MyClass(Vector3 position) { this.position = position; }
}

MyClass[] vertices = {
      new MyClass(new Vector3(0, 0, 0)),
      new MyClass(new Vector3(0, 0, 0)),
      new MyClass(new Vector3(2, 0, 2)),
      new MyClass(new Vector3(0, 0, 0)),
      new MyClass(new Vector3(2, 0, 2)),
      new MyClass(new Vector3(3, 0, 2)),
    };

var groupedSharedVertices = vertices
 .Select((vertex, i) => new {index = i, position = vertex.position})
 .GroupBy(vert => vert.position);

groupedSharedVertices[3].ToList().ForEach(x=> Debug.Log(x));

这有效,但没有给我我想要的数据:

{ 索引 = 3, 位置 = (0.5, 0.0, 0.5) }

{ 索引 = 6,位置 = (0.5, 0.0, 0.5) }

{ 索引 = 9, 位置 = (0.5, 0.0, 0.5) }

{ 索引 = 12,位置 = (0.5, 0.0, 0.5) }

相反,我想拥有:

{ (0.5, 0.0, 0.5): (3, 6, 9, 12) }

有什么好方法可以实现这个输出吗?

谢谢!

标签: c#linqunity3d

解决方案


这是你要找的吗?

var groupedSharedVertices = vertices
    .Select((x, i) => new { vert = x, index = i })
    .GroupBy(x => x.vert.position)
    .ToList();

groupedSharedVertices
    .ForEach(x => 
    Console.WriteLine($"{x.Key} : ({string.Join(", ", x.Select(x => x.index))})"));

输出:

<0, 0, 0> : (0, 1, 3)
<2, 0, 2> : (2, 4)
<3, 0, 2> : (5)

推荐阅读