简体   繁体   中英

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. 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. 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 .

Then your logic would be something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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