Understand the differences between the most commonly used interfaces for accessing and manipulating collections of data in C#.
The C# programming language provides excellent support for working with collections of data. C# includes several classes and interfaces that can help you query collections of data efficiently. The most commonly used interfaces for working with collections are IEnumerable, ICollection, IList, and IQueryable.
In this article we will examine each of these interfaces and discuss how we can work with them in .NET 8, illustrated with code examples.
First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project.We’ll use this .NET 8 console application project to work with the IEnumerable, ICollection, IList, and IQueryable interfaces in the subsequent sections of this article.
The IEnumerable interface in C# allows you to iterate over a collection of elements. It contains one method called GetEnumerator that returns an instance of type IEnumerable<T>. You can use this instance to iterate a collection of elements in a read-only, forward-only manner. You cannot use IEnumerable to iterate backwards.
The IEnumerable<T> interface is defined in the System.Collections namespace as shown below.When you execute the preceding piece of code, the names of the cities that start with the letter “L” will be displayed at the console window.
The ICollection interface is the base interface of all classes pertaining to the System.Collections namespace. It provides a generic collection of objects where the elements of the collection are accessible using an index.
The ICollection<T> interface is the generic equivalent of the ICollection interface. It extends the IEnumerable<T> interface, which in turn extends the IEnumerable interface as shown in the code snippet given below.Unlike the IEnumerable interface, the ICollection interface allows you to add or remove elements from a collection. The following code snippet shows how you can use the ICollection interface in C#.When you execute the above code, the country names added to the collection will be displayed at the console window.
The IList interface is available in the System.Collections namespace. It represents a strongly typed collection in which the elements of the collection are accessible using an index. IList extends the ICollection interface and contains additional methods such as IndexOf, Insert, and RemoveAt for working with collections.