TheAJ
TheAJ

Reputation: 10875

C# finding a certain condition of a object via a dictionary

Current i am using this method to determine if a character is online:

    public bool OnlineByServer(string username)
    {
        foreach (Character c in this.characters.Values)
        {
            if (c != null && c.Username.Equals(username))
            {
                return true;
            }
        }
        return false;
    }

Is there a faster way to do this?

Upvotes: 0

Views: 277

Answers (4)

Carra
Carra

Reputation: 17964

  • Finding an item by key: O(1)
  • Finding an item by value: O(n)

Upvotes: 0

thecoop
thecoop

Reputation: 46098

There isn't really a faster way of doing it, if you want to keep the characters as the dictionary Values. Due to being unsorted, a linear O(n) search has to be done.

Upvotes: 1

jestro
jestro

Reputation: 2593

    Dictionary<string, Character> usersByUsername = new Dictionary<string, Character>();

...

    if (usersByUsername.Keys.Contains(username))
    {

    }

Upvotes: 2

Rex M
Rex M

Reputation: 144122

The fastest way would be to make the username the key of the dictionary.

Upvotes: 9

Related Questions