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百科 (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)
精彩评论