나는 ICollection<MapNode>
이 있습니다. 각 MapNode
에는 Position
속성이 있으며 Point
입니다. 이 점을 먼저 Y 값으로 정렬 한 다음 X 값으로 정렬하고이를 다차원 배열 (MapNode[,]
)에 넣으려고합니다.C# : 컬렉션을 다차원 배열에 맞추는 깨끗한 방법?
컬렉션은 다음과 같이 보일 것입니다 :
(30, 20)
(20, 20)
(20, 30)
(30, 10)
(30, 30)
(20, 10)
그리고 최종 제품을 : 여기
(20, 10) (20, 20) (20, 30)
(30, 10) (30, 20) (30, 30)
내가 그것을 수행하는 때우기 코드입니다. 이 끔찍한 읽을 수 있습니까? 나는 그것이 필요 이상으로 해킹 된 것처럼 느낍니다.
private Map createWorldPathNodes()
{
ICollection<MapNode> points = new HashSet<MapNode>();
Rectangle worldBounds = WorldQueryUtils.WorldBounds();
for (float x = worldBounds.Left; x < worldBounds.Right; x += PATH_NODE_CHUNK_SIZE)
{
for (float y = worldBounds.Y; y > worldBounds.Height; y -= PATH_NODE_CHUNK_SIZE)
{
// default is that everywhere is navigable;
// a different function is responsible for determining the real value
points.Add(new MapNode(true, new Point((int)x, (int)y)));
}
}
int distinctXValues = points.Select(node => node.Position.X).Distinct().Count();
int distinctYValues = points.Select(node => node.Position.Y).Distinct().Count();
IList<MapNode[]> mapNodeRowsToAdd = new List<MapNode[]>();
while (points.Count > 0) // every iteration will take a row out of points
{
// get all the nodes with the greatest Y value currently in the collection
int currentMaxY = points.Select(node => node.Position.Y).Max();
ICollection<MapNode> ythRow = points.Where(node => node.Position.Y == currentMaxY).ToList();
// remove these nodes from the pool we're picking from
points = points.Where(node => ! ythRow.Contains(node)).ToList(); // ToList() is just so it is still a collection
// put the nodes with max y value in the array, sorting by X value
mapNodeRowsToAdd.Add(ythRow.OrderByDescending(node => node.Position.X).ToArray());
}
MapNode[,] mapNodes = new MapNode[distinctXValues, distinctYValues];
int xValuesAdded = 0;
int yValuesAdded = 0;
foreach (MapNode[] mapNodeRow in mapNodeRowsToAdd)
{
xValuesAdded = 0;
foreach (MapNode node in mapNodeRow)
{
// [y, x] may seem backwards, but mapNodes[y] == the yth row
mapNodes[yValuesAdded, xValuesAdded] = node;
xValuesAdded++;
}
yValuesAdded++;
}
return pathNodes;
}
위의 기능은 꽤 잘 작동하는 것으로 보이지만 아직 방탄 테스트를 거치지 않았습니다.
VB를 조금이라도 읽을 수 있습니다. 이미 쓰여 있다면 조금 있습니다. –