Choose between list or dictionary

My.NET application works with a collection of users. The user object contains the username, full name, domain ....

I wonder what type of collection I should prefer to store for users, between 1) List or 2) Dictionary, where the dictionary key is the username.

I understand that the dictionary option is the fastest when you want to extract a user from your username, but since the username is referenced, a consistency error may occur twice. (as a dictionary key and as a user attribute)? Could you also explain to me what are the differences from the design point of view?

+6
source share
4 answers

The best approach from a design point of view is to create a custom UserCollection class and hide the actual storage data. This gives you the ability to switch from a list to a dictionary without affecting other code. Suppose this is an extra layer of abstraction.

The differences between a list and a dictionary are conceptual. A simple rule is if the elements are unique and you need O (c) search complexity then use a dictionary, otherwise use a List.

+2
source

If you are usually looking for a user by UserName, then be sure to use a dictionary. Using the List, you must "trace" your path to the right one! As for consistency, I would use the Manager class, which would be the only one that allows you to manipulate the dictionary, thereby ensuring consistency. In many membership mechanisms, the username cannot be changed. Will this help your decision?

+3
source

It depends on the requirements, I think that for a smaller list the performance difference will be insignificant, and using List should be the preferred approach taking into account consistency, and you can have such a request.

var user = Users.SingleOrDefault(user => user.username == 'username') 
0
source

I prefer lists of objects, especially when data is stored in a database. The ability to query a data source and return a list is very useful. It is also preferred that the data is sequentially accessed, for example, with a data network.

Hope this helps.

0
source

Source: https://habr.com/ru/post/921679/


All Articles