Collections
Hi, I'm currently studying programming and I need help in C#. I don't really understand how to use lists and dictionary and when to pick which. Could somebody give me a bare bones explanation with an example of how to use it properly. Thanks in advance.
7 Replies
A List is used when you want a general collection and you don't know the size or want to be able to add and remove as needed
A Dictionary is also a collection but each value is represented with a unique key
So you see a Dictionary is literally a dictionary like in real life
A unique definition under a name with an explanation
In simple words, Dictionaries are built on top of Hash Table data structure, so this is a key, value pair collection. You have to define what kind of key,value pair you will store in the collection. While List, and Collection are built on top of Array.
Use arrays when you can use an index and the size is fixed. You get the elements to be consecutive in memory, which is efficient for iteration and simple to consider.
Use dynamic arrays (List<T>) when you need an array that can change size. It is possible to remove an element from a list, but you'll have to move elements to fill its place (either taking the element from the end, or moving the elements following the removed one one position towards the start). This is to conserve the consecutiveness property of arrays.
Use dictionaries when the key can't be an index. Either it's something like a string, or the items aren't consecutive, like some of the indices in the middle aren't used (it is sparse)
Or even better answer; make an application that requires certain collections and see which one solves an issue you might encounter
Because while a List and Dictionary are commonly used, you might end up requiring different types altogether (queue, bag, array, etc)
Thank you guys for explaining. how do i add stuff to a dictionary that has an int as a key and a list as value, I have a school project where i need to make a restaurant order app with 8 tables. I need to use dictionary's with a list of string as a value (for the orders) and the int is the table number. (sorry if my explanation isn't clear, english isn't my first language)
A dictionary takes two generic parameters.
Dictionary<TKey, TValue>
When you make a new dictionary, you specify these. in your case the first is an integer, and the second is the list type (List<string>
)
The dictionary has many methods, including methods to check for a key, getting a key, attempting to get a key, adding keysOkay, thank you for helping ๐