简体   繁体   English

如何检查字典是否在通用列表中包含值

[英]How to check if dictionary contains a value in a generic list

I have a list of coordinates that are stored in a generic list. 我有一个存储在通用列表中的坐标列表。 I want to be able to iterate through the list and check if any coordinates are adjacent to each other. 我希望能够遍历列表并检查是否有任何坐标彼此相邻。 If they are, then I know its from the same groups versus if they aren't. 如果是的话,那么我从相同的群体中知道是否存在。 Does anyone know how to do this properly? 有人知道如何正确执行此操作吗?

Update: Here's my updated code so far. 更新:这是到目前为止我更新的代码。 I am grouping coordinates in a new generic list and adding them to a dictionary if they are adjacent and also the same type. 我将坐标分组到一个新的通用列表中,如果它们相邻并且类型相同,则将它们添加到字典中。

Now I want to know if the Dictionary already contains the coordinate in a group. 现在,我想知道字典中是否已经包含一组坐标。 So it doesn't run the same process again. 因此,它不会再次运行相同的过程。 How do I access the values of the generic list in the dictionary? 如何访问字典中通用列表的值?

    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++;
        }   
    }

You probably want a better data structure to avoid the O(n^2) search. 您可能希望有更好的数据结构来避免O(n^2)搜索。 Maybe a 2D array? 也许是二维数组? The work required to construct it out of your current list might be worth it. 从当前列表中构造它所需的工作可能是值得的。

You also need to track the group ID for each point. 您还需要跟踪每个点的组ID。 This is because your isAdjacent function will not give you transitivity ie if three points differ by 1 unit in the x direction only, you want them in the same group but isAdjacent (p1, p3) will be false . 这是因为isAdjacent函数不会为您提供传递性,即,如果三个点仅在x方向上相差1个单位,则您希望它们在同一组中,但是isAdjacent (p1, p3)将为false

Then your logic would be something like 然后你的逻辑将是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM