MSDN Documentation

System.Collections.Generic Namespace

Namespace: System.Collections.Generic

Assembly: mscorlib.dll (in .NET Framework 4.8)

Contains interfaces and classes that define highly scalable data structures, such as lists, queues, dictionaries, and sets.

Classes

Interfaces

Common Usage Examples

Using List<T>

The List<T> class represents a strongly typed list of objects that can be accessed by index. It provides methods for adding, removing, searching, and sorting elements.

// Declare and initialize a list of strings List<string> names = new List<string>(); names.Add("Alice"); names.Add("Bob"); names.Add("Charlie"); // Iterate through the list foreach (string name in names) { Console.WriteLine(name); } // Access an element by index Console.WriteLine(names[0]); // Output: Alice

Using Dictionary<TKey, TValue>

The Dictionary<TKey, TValue> class stores key-value pairs. It provides efficient lookup, insertion, and deletion of elements based on their keys.

// Declare and initialize a dictionary of integers and strings Dictionary<int, string> studentGrades = new Dictionary<int, string>(); studentGrades.Add(101, "Alice"); studentGrades.Add(102, "Bob"); studentGrades.Add(103, "Charlie"); // Access a value by key Console.WriteLine(studentGrades[102]); // Output: Bob // Check if a key exists if (studentGrades.ContainsKey(101)) { Console.WriteLine("Student 101 found."); }

Using HashSet<T>

The HashSet<T> class stores a collection of unique elements. It provides efficient methods for adding, removing, and checking for the existence of elements, without duplicates.

// Declare and initialize a hash set of integers HashSet<int> uniqueNumbers = new HashSet<int>(); uniqueNumbers.Add(1); uniqueNumbers.Add(5); uniqueNumbers.Add(2); uniqueNumbers.Add(1); // This will be ignored as it's a duplicate // Check for element existence if (uniqueNumbers.Contains(5)) { Console.WriteLine("5 is in the set."); }