简体   繁体   中英

How to find a key from a dictionary

I have a dictionary which contains a key of type Wall and a value which is a List<Tile>

So it looks like this:

new Dictionary<Wall, List<Tile>>();

So i have a Tile and i am wanting to find all Wall types connected to this tile which is buried in the lists.

I don't fully understand how i iterate through the dictionary to do such a thing since the tile is then also inside the list. Should i not be using a Dictionary at all for this kind of data connection, i am not entirely sure if i am understanding dictionaries correctly here.

I do not think a Dictionary<Wall, List<Tile>> is the best data structure for solving this problem:

So i have a Tile and i am wanting to find all Wall types connected to this tile which is buried in the lists

You would have to use brute force (and very poor performance):

Dictionary<Wall, List<Tile>> dictionary; //todo initialize
List<Wall> result = new List<Wall>();
foreach (var kvp in dictionary) {
   if (kvp.Value.Contains(tile))
       result.Add(kvp.Key);
}

If you have a Tile and want to find a list of Walls, you would want Dictionary<Tile, List<Wall>> .

Dictionary<Tile, List<Wall>> dictionary; //todo initialize
List<Wall> result = dictionary[tile];

Which would leverage the power of the dictionary nicely.

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