Choosing Between IEnumerable and List in C#

diakingdev
1 min readFeb 22, 2023

When to Use Each IEnumerable and List

IEnumerable

Use IEnumerable when you need to work with a collection of items, but you don't necessarily need to know how many items are in the collection or be able to access them randomly.

IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

foreach (int number in numbers)
{
Console.WriteLine(number);
}

List

Use List when you need to work with an ordered collection of elements that you can index into or when you need to perform operations like adding, removing, or inserting elements.

List<string> selectedItems = new List<string>();

// User selects an item and adds it to the list
string newItem = "Apples";
selectedItems.Add(newItem);

// User selects another item and adds it to the list
string anotherItem = "Oranges";
selectedItems.Add(anotherItem);

// User removes the first item from the list
selectedItems.Remove(newItem);

// Print the remaining items in the list
foreach (string item in selectedItems)
{
Console.WriteLine(item);
}

--

--