Difference between IEnumerable and List

Learn via video courses
Topics Covered

Overview

In C#, developers have access to various data structures to handle collections of elements efficiently. Two commonly used data structures are IEnumerable and List. While both serve the purpose of managing collections, they have distinct characteristics and are suited for different scenarios. In this article, we will explore the IEnumerable vs List, their appropriate use cases, and a performance comparison to help developers make informed decisions when selecting the right data structure.

What is IEnumerable?

IEnumerable is an interface in C# that is part of the System.Collections namespace. It stands for a collection of elements that can only be read and forwarded. The main function of an IEnumerable is to allow foreach loops or LINQ queries to iterate over a collection. It is frequently used for large-scale data processing and querying without the need for index-based access. IEnumerable is implemented by various collection types, such as arrays, lists, and dictionaries, allowing them to be iterated in a standardized manner. One of the key features of IEnumerable is its deferred execution, which means the elements are fetched only when needed during iteration, leading to better memory utilization in certain scenarios.

Example:

Let's see a simple example of how to use IEnumerable with a basic collection of integers.

Output

In this example, we have an array numbersArray containing five integer elements. We then create an IEnumerable<int> called enumerableNumbers and assign the numbersArray to it.

The foreach loop iterates over enumerableNumbers, and in each iteration, it fetches the next element from the array and assigns it to the variable number. The loop continues until all elements have been processed.

What is List

List is a class in C# that also resides in the System.Collections.Generic namespace. It implements the IList interface and provides a dynamic array that can grow or shrink in size based on the number of elements it contains. List is a more versatile and feature-rich data structure compared to IEnumerable.

With List, developers have access to index-based access, allowing efficient random access to elements. It provides a wealth of methods for adding, removing, and manipulating elements within the collection. While talking about ienumerable vs list, List is an ideal choice when you need to frequently modify the collection or access elements using their index.

Example:

Let's see a simple example of list

Output

This example adds three members (10, 20, and 30) to a List<int> named numbersList by using the Add function. Then, we use numbersList[0] and numbersList[1] to access the first and second entries using index-based access and report their values to the console.

Key differences: IEnumerable Vs List

  • Mutability: When we talk about mutability in IEnumerable vs List ,IEnumerable is immutable and read-only. The collection's elements cannot be added, removed, or modified after it has been initialised. The ability to add, remove, and update elements on a list gives you more freedom when managing your data.
  • Indexing: Since direct indexing is not supported by IEnumerable, it is less suitable for situations involving frequent random access to elements. Indexing is supported by list, allowing quick and easy access to elements based on their index position.
  • Memory Usage: When working with huge datasets with IEnumerable vs List, IEnumerable uses deferred execution, which might result in better memory utilisation because elements are only obtained when required. Due to its resizable nature, list, being a dynamic array, could have a greater memory overhead.
  • Performance: IEnumerable generally performs better in terms of performance when used with LINQ queries and foreach loops because it prevents needless memory allocation and copying whereas Lists are more effective since they give you direct access to the items and are used frequently when index-based access and adjustments are needed.
  • Usage Scenarios: IEnumerable is appropriate in situations where LINQ queries on huge datasets and read-only access to elements are the main concerns. When you regularly need to add, remove, or update elements and when random access to elements based on their index is essential, a list is preferred.

When to Use Each One

Consider the following while choosing between IEnumerable vs List:

Choose IEnumerable when:

  • You need to work with large datasets and prefer deferred execution to optimize memory usage.
  • Read-only access to elements is sufficient for your use case.
  • You plan to utilize LINQ queries extensively.

Choose List when:

  • You need to perform frequent modifications on the collection, such as adding, removing, or updating elements.
  • Fast, random access to elements based on their index is essential.
  • You require a dynamic data structure that can resize as the number of elements changes.

It's also useful to know that the ToList() and AsEnumerable() functions allow you to convert between IEnumerable and List.

Example:

Let's see a simple example of IEnumerable vs List conversion

Output

In this code, an IEnumerable<int> called enumerableNumbers is first created by utilising a List<int> of five integers. To explicitly transform enumerableNumbers into a List<int> named numbersList, we utilise the ToList() function. The numbersList's components are then printed.

Then, we make a List<int> called numbersList2 that has five more integers in it. We directly transform numbersList2 into an IEnumerable<int> named enumerableNumbers2 using the AsEnumerable() method. Finally, we print the enumerableNumbers2's elements.

Performance

When you use IEnumerable, you are using deferred execution, which means that the real operations are executed when you begin iterating over the collection. This can improve memory efficiency because things are retrieved one at a time rather than being stored in memory all at once. However, deferred execution might cause performance concerns, particularly if the same enumeration is done numerous times whereas The IEnumerable interface is concretely implemented by List. It is a dynamic array that allows for quick access to elements through index, insertion, and removal operations. List, in contrast to IEnumerable, stores all of its elements in memory, which can result in increased memory consumption when compared to IEnumerable implementations that use postponed execution.

  • Memory Consumption:

    • IEnumerable: Uses less memory since it runs in a deferred manner, fetching things one at a time.
    • List: Uses more memory because all elements are stored in memory at the same time.
  • Iteration Performance:

    • IEnumerable: Iterating over an IEnumerable may entail more method calls and be slightly slower than iterating over a List, depending on the exact implementation.
    • List: Provides faster iteration speed due to direct array-like index access.
  • Querying and Operations:

    • IEnumerable: Ideal for using LINQ (Language Integrated Query) to query and manipulate data. Multiple LINQ operations, on the other hand, can result in multiple enumerations, potentially affecting performance.

    • List: Provides efficient querying and manipulation operations due to its direct access to elements. It's especially efficient for scenarios that require multiple iterations or changes to the collection.

Direct comparison between IEnumerable and List

Let's compare and break down the code that shows how to utilise IEnumerable<T> and List<T> when iterating through an array of numbers.

Example

Output

In this case:

  • We make a number array and demonstrate operations on both IEnumerable<T> and List<T>.
  • Using the PrintCollection function, we demonstrate how IEnumerable<T> and List<T> may be used to iterate through collections.
  • The array is converted to a List<int>, an element is added, and the changed list is printed.
  • We remove an item from the list, reprint it, and display the modified list.
  • We use LINQ to filter the list for even integers and then publish the results.

This example compares IEnumerable<T> and List<T> in depth by illustrating their abilities to perform typical operations on a collection of numbers.

  • Using IEnumerable to Iterate through Array:
    • First, we use implicit conversion to convert the array numbersArray into an IEnumerable<int> named enumerableNumbers.
    • Without being aware of the underlying implementation details, it is possible to iterate through a collection using the IEnumerable<int> interface. Deferred execution is used during iteration to fetch the elements one at a time; the entire array is not loaded into memory at once.
    • We use enumerableNumbers to go through the array and print each element to the terminal in the foreach loop.
  • Using List Directly to Iterate:
    • To go through its contents, we directly use the List named numbersList in a foreach loop.

    • Direct indexing is supported by List, and the elements are kept in contiguous memory for quick and constant-time access during iteration.

    • Each element of the numbersList is printed to the console by the foreach loop as it iterates over the list.

The fundamental distinction is in the flexibility and use of memory:

  • The array cannot be enlarged because it has a set size. This could result in memory loss if the array is given more space than is necessary while working with a big number of elements.
  • Due to its ability to dynamically expand and contract, the List<int> is more adaptable. When an element is added or withdrawn, it automatically handles resizing, saving memory when the collection's size fluctuates regularly.

Conclusion

  • IEnumerable and List are data structures for managing collections in C#.
  • IEnumerable is excellent for LINQ queries on huge datasets because it is read-only and offers postponed execution.
  • Lists are mutable and feature indexing, making them perfect for sporadic changes and random access.
  • IEnumerable is memory-efficient, while List may have higher memory overhead due to resizing.
  • List thrives at random access and alterations whereas IEnumerable does well with LINQ and foreach loops.
  • Use IEnumerable for read-only access and optimized memory usage.
  • Use List if you require quick, index-based access and frequent updates.
  • When iterating, IEnumerable performs somewhat better than List, although List is quicker when adding elements.