DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering List Enumeration in C#: Full Code Examples

When working with collections in C#, enumeration and manipulation of lists are fundamental skills. This article will cover key concepts: displaying ordered data, enumerating backward, and systematically removing elements, with complete code examples.


1. Displaying the Order When Enumerating

Displaying the position of each element in an ordered list is a common requirement. However, C# uses zero-based indexing, which can be confusing for users. Here's how to adjust for 1-based indexing.

Code Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> countries = new List<string> 
        { 
            "China", "India", "USA", "Indonesia", "Pakistan", 
            "Brazil", "Nigeria", "Bangladesh", "Russia", "Mexico" 
        };

        Console.WriteLine("Countries in Order:");
        for (int i = 0; i < countries.Count; i++)
        {
            Console.WriteLine($"{i + 1}: {countries[i]}"); // 1-based index
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Countries in Order:
1: China
2: India
3: USA
4: Indonesia
5: Pakistan
6: Brazil
7: Nigeria
8: Bangladesh
9: Russia
10: Mexico
Enter fullscreen mode Exit fullscreen mode

2. Enumerating Backwards

Sometimes, you need to iterate through a list in reverse order. This requires starting at the last index and decrementing.

Code Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> countries = new List<string> 
        { 
            "China", "India", "USA", "Indonesia", "Pakistan", 
            "Brazil", "Nigeria", "Bangladesh", "Russia", "Mexico" 
        };

        Console.WriteLine("\nCountries in Reverse Order:");
        for (int i = countries.Count - 1; i >= 0; i--)
        {
            int displayIndex = countries.Count - i; // Adjusted for display
            Console.WriteLine($"{displayIndex}: {countries[i]}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Countries in Reverse Order:
1: Mexico
2: Russia
3: Bangladesh
4: Nigeria
5: Brazil
6: Pakistan
7: Indonesia
8: USA
9: India
10: China
Enter fullscreen mode Exit fullscreen mode

3. Systematically Removing Elements from a List

Removing items from a list during iteration can be tricky because indexes shift. One solution is to iterate backward.

Code Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> countries = new List<string> 
        { 
            "China", "India", "USA", "Indonesia", "Pakistan", 
            "Brazil", "Nigeria", "Bangladesh", "Russia", "Mexico" 
        };

        Console.WriteLine("\nRemoving countries with names shorter than 5 characters:");

        for (int i = countries.Count - 1; i >= 0; i--) // Iterate backward
        {
            if (countries[i].Length < 5)
            {
                Console.WriteLine($"Removing: {countries[i]}");
                countries.RemoveAt(i);
            }
        }

        Console.WriteLine("\nRemaining Countries:");
        foreach (var country in countries)
        {
            Console.WriteLine(country);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Removing countries with names shorter than 5 characters:
Removing: USA
Removing: India
Removing: China

Remaining Countries:
Indonesia
Pakistan
Brazil
Nigeria
Bangladesh
Russia
Mexico
Enter fullscreen mode Exit fullscreen mode

4. Combining Operations: Displaying and Filtering

You can combine enumeration with filtering. For example, display countries longer than five characters in reverse order.

Code Example

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> countries = new List<string> 
        { 
            "China", "India", "USA", "Indonesia", "Pakistan", 
            "Brazil", "Nigeria", "Bangladesh", "Russia", "Mexico" 
        };

        Console.WriteLine("\nFiltered and Reversed List:");
        for (int i = countries.Count - 1; i >= 0; i--)
        {
            if (countries[i].Length > 5)
            {
                int displayIndex = countries.Count - i;
                Console.WriteLine($"{displayIndex}: {countries[i]}");
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Filtered and Reversed List:
1: Mexico
2: Russia
3: Bangladesh
4: Nigeria
5: Pakistan
6: Indonesia
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. Control with for loops: Use the loop index to manage display order and modify it for user-friendly 1-based indexing.
  2. Iterate backward safely: When removing elements, reverse iteration prevents skipped or missed items.
  3. Flexibility with loops: Combine operations like filtering, enumeration, and ordering for custom requirements.

Top comments (0)