c# - 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) }
有什么好方法可以实现这个输出吗?
谢谢!
解决方案
这是你要找的吗?
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)
推荐阅读
- google-apps-script - 如何修复谷歌脚本中的“getNextDataCell下一个跳过一个单元格”错误
- amazon-web-services - AWS CloudFormation:AWS::Events::Rule - InputTemplate
- json - CSV 数据(不是文件)到 json
- ios - iOS 13 Public Beta 2 - Combine.Future "dyld: Symbol not found"
- web-component - children 和 parentNode 命令不适用于 Web 组件
- mysql - 如何选择从伦敦向所有项目出售 P1 件的供应商?
- python - Firebase Firestore:获取生成的文档 ID(Python)
- java - 使用 flyway 命令行版本索引
- android - 动画片段上滑和下滑
- python-3.x - 如何替换以下代码:predictions_ARIMA_log = pd.Series(indexedDataset_logScale['MH'].ix[0], index = indexedDataset_logScale.index)