Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose between List or Dictionary

Tags:

c#

collections

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?

like image 827
jkf2 Avatar asked Jul 30 '12 14:07

jkf2


2 Answers

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?

like image 116
Raphael Gabbarelli Avatar answered Sep 30 '22 12:09

Raphael Gabbarelli


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.

like image 40
Tony Kh Avatar answered Sep 30 '22 11:09

Tony Kh