Course Content
C# Tutorial
About Lesson

Manipulating and iterating through collections

Collection manipulation forms a fundamental aspect of C# programming, enabling developers to efficiently handle and iterate through various data structures. Whether dealing with arrays, lists, dictionaries, or other collections, mastering these manipulation techniques significantly enhances code flexibility and performance.

Understanding Collections in C#

C# offers an array of collection types, each serving distinct purposes. Arrays represent fixed-size collections, while lists provide dynamic resizing capabilities. Dictionaries facilitate key-value pair storage, and other collections like queues and stacks cater to specific data handling requirements.

Iterating Through Collections

  1. For Loops: The traditional for loop proves effective for iterating through arrays and lists. Its structured approach allows direct access to elements using index values.

    for (int i = 0; i < collection.Length; i++)
    // Accessing collection elements: collection[i]
  2. Foreach Loops: Especially useful for iterating through collections without the need for explicit index handling. Foreach loops simplify traversal, enhancing code readability.

    foreach (var item in collection)
    // Accessing each item in the collection: item

Collection Manipulation Techniques

  1. Adding Elements: Collections often require dynamic updates. For lists, the Add() method efficiently inserts elements.

  2. Removing Elements: The Remove() method, primarily for lists, allows targeted removal of elements.

  3. Sorting Collections: Sorting arrays and lists is achievable through methods like Sort().


Advanced Collection Manipulation

  1. LINQ (Language Integrated Query): LINQ offers powerful querying capabilities, enabling filtering, sorting, and transformation operations on collections.

    var filteredList = collection.Where(item => item.Property == value).ToList();
  2. Custom Iteration Techniques: Implementing custom iterators using yield return facilitates unique ways of traversing collections, offering tailored functionalities.

    IEnumerable<string> CustomIterator()
    // Custom logic to yield elements
    yield return element;