Skip to content

Instantly share code, notes, and snippets.

@jv-amorim
Last active April 26, 2020 16:51
Show Gist options
  • Save jv-amorim/b52951ecd156272746adf482e0a08a63 to your computer and use it in GitHub Desktop.
Save jv-amorim/b52951ecd156272746adf482e0a08a63 to your computer and use it in GitHub Desktop.
Notes about C# Collections.

📌️ C# Collections Notes

📄️ Lists:

✅️ The FindIndex() method can receive a lambda function as an argument and, thus, it's possible find the first unknown element that meets a desired requirement, present in the lambda function. Example: int brazilIndex = countries.FindIndex(x => x.Population < 220_000_000);

✅️ The Insert() method allows the insertion of an element after a desired index in the list. Example:

Country lilliput = new Country("Lilliput", 2_000_000);
countries.Insert(brazilIndex, lilliput);

✅️ It is necessary to be careful when using lists, because misuse can cause performance problems when inserting and removing items in large lists, since in these operations, all data must be moved in memory (the allocation of the list in memory is sequential). When using the Add operation, there is no problem, because no data needs to be moved in memory.

✅️ Enumerating/iterating a collection is synonymous with going through all the items in that collection.


📕️ Dictionaries:

✅️ Collection based in key-value concept.

✅️ Look up items with a key.

✅️ Great for unordered data (no index needed to retrieve a value).

✅️ Dictionary<TKey, TValue>.

✅️ Dictionaries have the Add() method, like lists, but not the Insert() method, because insertion doesn't make sense, as the items are not ordered in this collection.

✅️ In dictionaries the method TryGetValue() can be used when we don't known if a key-value actually exists in the dictionary. The method return a true bool if the element exists and false if not. Example:

bool exists = countries.TryGetValue("EUA", out Country country);

In the exemple above, the second parameter have the "out" keyword, so this parameter will exist outside of this method call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment