开发者

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

开发者 https://www.devze.com 2022-12-13 03:01 出处:网络
Current i am using this method to determine if a character is online: public bool OnlineByServer(string username)

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百科 (c != null && c.Username.Equals(username))
            {
                return true;
            }
        }
        return false;
    }

Is there a faster way to do this?


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


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

...

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

    }


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消