【问题标题】:How to check if dictionary contains a value in a generic list如何检查字典是否包含通用列表中的值
【发布时间】:2013-05-19 03:43:02
【问题描述】:

我有一个存储在通用列表中的坐标列表。我希望能够遍历列表并检查是否有任何坐标彼此相邻。如果他们是,那么我知道它来自同一组而不是如果他们不是。有谁知道如何正确执行此操作?

更新: 到目前为止,这是我更新的代码。我将坐标分组到一个新的通用列表中,如果它们相邻并且类型相同,则将它们添加到字典中。

现在我想知道字典是否已经包含组中的坐标。所以它不会再次运行相同的过程。如何访问字典中通用列表的值?

    private void groupMatchTile(List<int[]> matchTile){
        int i = 0;
        Dictionary<int, List<int[]>> groups = new Dictionary<int, List<int[]>>();

        foreach(int[] coord in matchTile){
            if(groups.ContainsValue(

            // How do you check if the coords already belong in a group

            )) return;

            groups.Add(i, new List<int[]>());   
            groups[i].Add(coord);

            foreach(int[] nextCoord in matchTile){
                if (coord == nextCoord) return;
                else {
                    if (    isAdjacent(coord[0], coord[1], nextCoord[0], nextCoord[1]) &&
                            level.grid[coord[0], coord[1]] == level.grid[nextCoord[0], nextCoord[1]]
                    ){
                        groups[i].Add(nextCoord);   
                    }
                }
            }

            i++;
        }   
    }

【问题讨论】:

  • 很难理解你的代码。有很多对象对我们来说是未定义的。你的代码有什么问题?您需要向我们提供更多信息。描述你目前的情况。
  • 好的。我现在实际上正在研究它。我想我明白了如何解决这个问题的要点。一旦我走得更远,我会更新这篇文章。感谢您的注意。

标签: c# foreach coordinates generic-list


【解决方案1】:

您可能需要更好的数据结构来避免O(n^2) 搜索。也许是一个二维数组?从您当前的列表中构建它所需的工作可能是值得的。

您还需要跟踪每个点的组 ID。这是因为您的 isAdjacent 函数不会为您提供传递性,即如果三个点仅在 x 方向上相差 1 个单位,您希望它们在同一组中,但 isAdjacent (p1, p3) 将是 false

那么你的逻辑会是这样的

if (isAdjacent (point1, point2)) {
    point1.groupID = point2.groupID = min (point1.groupID, point2.groupID)
}

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 2020-05-09
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多