Collections - mcbride-clint/DeveloperCurriculum GitHub Wiki

Collections in .Net has been a growing group of classes that make it easier to store, manage, and manipulate data. Each type that has been added have different use cases that provide advantages and disadvantages depending on what you want to do with the data.

Common Types

List<T> is one of the most common collections that can be seen as an easier way to work with arrays. Once a List is declared, items of it's Generic Type can be added and removed as needed without having to worry about array size and current index position. Lists will manage these needs for you in the background.

// Create a new list
List<User> users = new List<User>();

// Create a new User
User newUser = new User("John");

// Add User to List
users.Add(newUser);

int numOfUsers = users.Count(); // 1 User in List

// Remove User from List by reference
users.Remove(newUser);

Dictionary<TKey, TValue> is another useful collection that forms Key Value pairs where the type of Key and Values are set when initialized. It can help to associate a key with each entry in a collection to enforce a unique constraint.

// Create a new Dictionary
Dictionary<int, User> users = new Dictionary<int, User>();

// Create a new User
User newUser = new User("John");

// Add User to Dictionary
users.Add(1, newUser);

int numOfUsers = users.Keys.Count(); // 1 User in List

// Remove User from Dictionary by key
users.Remove(1);

Collections come in both Generic and Non-Generic Types. Generic Types provide performance increases and compile time safety so they should always be used over their Non-Generic counterparts.

Generic Non-Generic
List<T> ArrayList
Dictionary<TKey ,TValue> HashTable

Other collections include:

  • HashSet
  • LinkedList
  • SortedDictionary
  • SortedList
  • Stack
  • Queue

More information about these types can be found in the Microsoft Docs below.

See Also

⚠️ **GitHub.com Fallback** ⚠️