How to use IEnumerable, ICollection, IList, and IQueryable in C#
By FoxLearn 1/2/2025 9:12:19 AM 237
In this article, we will learn how to work with the IEnumerable, ICollection, IList, and IQueryable interfaces.
The IEnumerable interface in C#
The IEnumerable interface in C# enables iteration over a collection of elements in a read-only, forward-only manner. It includes a method called GetEnumerator, which returns an instance of IEnumerator to iterate through the collection.
However, IEnumerable does not support backward iteration. It is defined in the System.Collections namespace.
public interface IEnumerable<out T> : IEnumerable { new IEnumerator<T> GetEnumerator(); }
For example:
List<int> numbers = new List<int> { 5, 10, 15, 20, 25, 30, 35, 40 }; IEnumerable<int> divisibleByFive = numbers.Where(n => n % 5 == 0); foreach (var number in divisibleByFive) { Console.WriteLine(number); }
In this new example, the program filters the list of numbers to display only those divisible by 5.
The output will be: 5, 10, 15, 20, 25, 30, 35, 40.
The ICollection interface in C#
The ICollection interface is the base interface for all classes in the System.Collections namespace, providing a generic collection of objects where elements can be accessed using an index. It extends the IEnumerable interface, which enables iteration over the collection. The generic version of ICollection, ICollection, allows for type-safe collections of objects.
public interface ICollection<T> : IEnumerable<T> { int Count { get; } bool IsReadOnly { get; } void Add(T item); void Clear(); bool Contains(T item); void CopyTo(T[] array, int arrayIndex); bool Remove(T item); }
Unlike the IEnumerable interface, the ICollection interface allows you to modify a collection by adding or removing elements. This makes it more versatile for managing collections.
The following code snippet demonstrates how to use the ICollection interface in C# to manipulate a collection.
ICollection<int> numbers = new Collection<int>(); numbers.Add(10); numbers.Add(20); numbers.Add(30); numbers.Add(40); foreach (int number in numbers) { Console.WriteLine(number); }
In this example, the program creates a collection of numbers, adds several values to it, and then displays each number at the console window. When executed, the output will be:
10 20 30 40
The IList interface in C#
The IList interface, found in the System.Collections namespace, represents a strongly typed collection where elements are accessible by index. It extends the ICollection interface and adds additional methods such as IndexOf, Insert, and RemoveAt, which provide more control for working with collections. These methods allow for indexed access and manipulation of elements in the collection.
public interface IList : ICollection { Object this[int index] { get; set; } int Add(Object value); bool Contains(Object value); void Clear(); bool IsReadOnly { get; } bool IsFixedSize { get; } int IndexOf(Object value); void Insert(int index, Object value); void Remove(Object value); void RemoveAt(int index); }
The following code snippet demonstrates how to create an instance of the IList type, and then add and remove elements from the collection:
IList<string> fruits = new List<string>(); fruits.Add("Apple"); fruits.Add("Banana"); fruits.Add("Orange"); fruits.Remove("Banana"); foreach (var fruit in fruits) { Console.WriteLine(fruit); }
This code adds fruits to the collection and removes "Banana," then prints the remaining elements, showing "Apple" and "Orange" in the output.
The IQueryable interface in C#
The IQueryable interface, part of the System.Linq namespace, extends the IEnumerable interface. It is used to query data from data sources that implement IQueryable providers. This interface allows for more advanced querying capabilities, such as deferred execution, and is commonly used with LINQ to query databases or other data sources efficiently.
public interface IQueryable<out T> : IEnumerable<T>, IQueryable { }
The IEnumerable interface is typically used for working with in-memory collections of data, while the IQueryable interface is designed for querying external data sources, such as web services or databases. IQueryable allows for more efficient querying and deferred execution, making it suitable for working with large or remote data sources.
Here’s example demonstrating how to work with the IQueryable interface in C#:
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public bool InStock { get; set; } } List<Product> products = new List<Product>() { new Product(){Id = 1, Name = "Laptop", Price = 1000, InStock = true}, new Product(){Id = 2, Name = "Phone", Price = 500, InStock = false}, new Product(){Id = 3, Name = "Tablet", Price = 300, InStock = true} }; IQueryable<Product> query = products.AsQueryable() .Where(p => p.InStock == true) .OrderBy(p => p.Price); foreach (var product in query) { Console.WriteLine($"Id: {product.Id} Name: {product.Name} Price: {product.Price}"); }
This example filters the Product collection to display only items that are in stock and sorts them by price. When executed, it will output the products that are available, sorted from lowest to highest price.
Choosing the Right Collection Interface
Here’s a quick summary of the IEnumerable, ICollection, IList, and IQueryable interfaces:
- IEnumerable: Allows read-only, forward-only access to elements of a collection without modifying them.
- ICollection: Inherits from IEnumerable and adds functionality for adding, deleting, and modifying elements.
- IList: Extends ICollection and supports strongly typed collections accessible via an index, and allows insertion, removal, and modification of elements by index.
- IQueryable: Extends IEnumerable and supports LINQ, making it ideal for querying large datasets or working with data sources like databases, where queries are translated to data layer operations.
The choice of interface depends on the requirements of your application IQueryable is best for querying external data sources, while IEnumerable, ICollection, and IList are suitable for in-memory collections, with varying levels of modification support.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#