Generic Collection with Dictionary and List in C#

Collections

C# includes various classes that store the values or objects called collections.

There are two types of collections available in C#.

Non-generic collections and Generic collections

The System. The collections namespace contains the non-generic collection types and systems.Collections.Generic namespace includes generic collection types.

In most cases, it is recommended to use the generic collections because they perform faster than non-generic collections and also minimize exceptions by giving compile-time errors.

Non-generic Collections: HashSet, Sorted List, Dictionary, List

Dictionary

The dictionary is a generic collection that is generally used to store key/value pairs.

Dictionary<int, string> dictionary_name = new Dictionary<int, string>();

// Adding key/value pairs in the Dictionary using Add() method
dictionary_name.Add(1123, "Welcome");
dictionary_name.Add(1124, "to");
dictionary_name.Add(1125, "India");
 
foreach(KeyValuePair<int, string> element in dictionary_name)
{
    Console.WriteLine("{0} and {1}", element.Key, element.Value);
}
Console.WriteLine();

Remove

// Using Remove() method 
My_dict.Remove(1123);

Clear

// Using Clear() method
My_dict.Clear();

List

A list is a collection of objects accessed using their index.

Creating a List

List<int> primeNumbers = new List<int>();

// Adding elements using Add() method
primeNumbers.Add(2);
primeNumbers.Add(3);
primeNumbers.Add(5);
primeNumbers.Add(7);

Access elements from a list

List<int> numbers = new List<int>() { 1, 2, 5, 7, 8, 10 };

Console.WriteLine(numbers[0]); // prints 1
Console.WriteLine(numbers[1]); // prints 2
Console.WriteLine(numbers[2]); // prints 5
Console.WriteLine(numbers[3]); // prints 7

Remove element from the list

var numbers = new List<int>() { 10, 20, 30, 40, 10 };

numbers.Remove(10); // removes the first 10 from a list

Contains

var numbers = new List<int>() { 10, 20, 30, 40 };

numbers.Contains(10); // returns true

Happy Coding!

Thanks