My .NET application works with collection of users. A User object contain the username, the fullname, the domain....
I wonder which type of collection should I prefer to store the users, between a 1) List or 2) Dictionary, where the dictionary key is the username.
I understand that the dictionary option is fastest when having to retrieve a user from its username, but because the username is referenced twice consistency error might occurs. (as dictionary key and as user attribute)? Could you also explain me what are the differences from a design point of view?
If you usually seek a user by UserName, then definitely use a Dictionary. Using a List you'd have to "foreach" your way to the right one! As for consistency, I'd implement a Manager class that would be the only allowed to manipulate the dictionary, thus enforcing consistency. In many membership engines, the username cannot be changed. Would that help your solution?
The best approach from design point of view is to create a custom class UserCollection and hide the actual storage details. This gives you an ability to change from List to Dictionary without impact to other code. Suppose it is an additional layer of abstraction.
The differences between List and Dictionary are conceptual. Simple rule - if items are unique and you need a O(c) search complexity then use a Dictionary, otherwise use a List.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With