.NET Core API Documentation

Learn about the core libraries of .NET Core.

Namespace: System.Collections

Namespace: System.Collections
Assembly: System.Runtime

Provides interfaces and classes that define collections of objects, such as lists, queues, arrays, hash tables, and dictionaries.

Summary of Types

Type Name Description
ICollection<T> Represents a strongly typed collection of objects that can be accessed by index.
IEnumerable<T> Exposes an enumerator, which supports a simple iteration over a collection of a specified type.
IDictionary<TKey, TValue> Represents a collection of key/value pairs that are sorted by key.
IList<T> Represents a non-generic collection of objects.
List<T> Represents a strongly typed list of objects that can be accessed by index.
Dictionary<TKey, TValue> Represents a collection of key/value pairs that are organized by key.
Hashtable Represents a collection of key/value pairs that are ordered by key. (Non-generic)

Usage Example

Here's a basic example of using the List<T> class:


using System;
using System.Collections.Generic;

public class Example
{
    public static void Main(string[] args)
    {
        // Create a list of strings
        List names = new List();

        // Add elements to the list
        names.Add("Alice");
        names.Add("Bob");
        names.Add("Charlie");

        // Iterate through the list
        Console.WriteLine("Names in the list:");
        foreach (string name in names)
        {
            Console.WriteLine($"- {name}");
        }

        // Access an element by index
        Console.WriteLine($"\nThe second name is: {names[1]}");

        // Remove an element
        names.Remove("Bob");

        // Check if an element exists
        if (names.Contains("Charlie"))
        {
            Console.WriteLine("\nCharlie is still in the list.");
        }
    }
}
                

Key Concepts

  • Generics: The System.Collections.Generic namespace provides generic collection types (e.g., List<T>, Dictionary<TKey, TValue>) that offer type safety and better performance compared to their non-generic counterparts.
  • Interfaces: Common interfaces like IEnumerable<T>, ICollection<T>, and IList<T> define contracts for collection behavior, enabling polymorphism.
  • Data Structures: This namespace includes fundamental data structures like lists, dictionaries, and hash tables, crucial for managing collections of data efficiently.