0

today i have a big problem and a heartache...

I have a problem with Dictionary. I wan't to receipt retrieve a Name of a "room" (it's the system) with and ID, but i have this structure:

class RoomManager
{
    public readonly Dictionary<uint, Room> _rooms;

    public RoomManager()
    {
        _rooms = new Dictionary<uint, Room>();

        AddRoom(new Room(1, "den.png", "The Den", 1));
        AddRoom(new Room(2, "disco.png", "Disco", 1));
        AddRoom(new Room(3, "brunch.png", "Brunch", 2));
        AddRoom(new Room(4, "disco.png", "Disco 2", 3));
    }

    public Dictionary<uint, Room> GetRooms()
    {
        return _rooms;
    }


    public bool AddRoom(Room room)
    {
        if (_rooms.ContainsKey(room.ID))
        {
            return false;
        }
        _rooms.Add(room.ID, room);
        return true;
    }



}

And the most important:

class Room
{
    public uint ID;
    public string Codename;
    public string Name;
    public int Category;

    public Room(uint id, string codename, string name, int category)
    {
        ID = id;
        Codename = codename;
        Name = name;
        Category = category;
    }
}

It's a system with Socket, so with the adding of Room, all is display on a webpage and when i click on it, the website send me the ID and me, i want to display in the Console the name of "Room clicked"!

So in conclusion: How do I retrieve with a function the name of it with his ID?

3
  • 1
    What is your problem ? Commented Apr 3, 2014 at 16:51
  • 1
    What is the question or problem? Commented Apr 3, 2014 at 16:52
  • If I understood correct, and it's really hard to do do, you are searching for the index of a dictionary? Try this _rooms[3].Name Commented Apr 3, 2014 at 16:57

1 Answer 1

3

If I understand your question correctly, this code should work

public String getRoomName(uint id)
{
  string name;
  return _rooms.TryGetValue(id, out name) ? name : "";
  // Have an empty string to catch exceptions (this part isn't necessary but it could be helpful if you don't know that the room exists)
}
Sign up to request clarification or add additional context in comments.

3 Comments

using String.Empty is nearly always preferable to using "" as it avoids the unnecessary extra literal.
ContainsKey followed by indexer can always be improved by calling TryGetValue
@focuspark have you tried: ReferenceEquals(String.Empty, "") ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.