.NET Tips List vs IEnumerable

Abhishek Malaviya
2 min readJul 31, 2023

--

As we know IList implements IEnumerable. Now we will explore a practical use case for utilizing both

IList

By using IEnumerable, you allow the compiler to smartly defer tasks, potentially optimizing them as it goes. IEnumerable will not execute the query until you enumerate over the data.

But when you opt for List, you force the compiler to immediately materialize the results and keep it in memory.

Use Case

When you have a scenario where you need to enumerate the data only once, using IEnumerable is the more efficient and faster option. It allows for deferred execution, ensuring data retrieval happens only when needed.

On the other hand, if you have a situation where you need to enumerate the data multiple times, the List becomes more efficient. Since it stores all the data in memory, there’s no need to recompute or re-query the data during each enumeration.

Let us verify the following sample code:

internal class TestCollection
{
internal List<Person> BuildPersonList()
{
List<Person> personList = new()
{
new Person
{
Name = "Robert White",
Age = 35,
City = "London"
},
new Person
{
Name = "Gopal Das",
Age = 40,
City = "Chennai"
},
new Person
{
Name = "Alex",
Age = 20,
City = "Paris"
}
};

return personList;
}
}

internal class Person
{
internal required string Name { get; set; }
internal int Age { get; set; }
internal required string City { get; set; }
}

//Run example

TestCollection testCollection = new();
var persons = testCollection.BuildPersonList();

IEnumerable<Person> personIEnumerable = persons.Where(p => p.Age > 30);

List<Person> personList = persons.Where(p => p.Age > 30).ToList();

persons.Add(new Person
{
Name = "John",
Age = 40,
City = "New York"
});

Console.WriteLine($"IEnumerable Example\nPerson Count: {personIEnumerable.Count()}");

Console.WriteLine($"\nList Example\nPerson Count: {personList.Count}");

Output

IEnumerable vs List

Happy coding. Thanks for reading.

--

--

No responses yet