6.6 C
New York
Friday, January 12, 2024

Find out how to use IEnumerable, ICollection, IList, and IQueryable in C#


The C# programming language offers wonderful help for working with collections of knowledge. C# contains a number of lessons and interfaces that may show you how to question collections of knowledge effectively. Probably the most generally used interfaces for working with collections are IEnumerable, ICollection, IList, and IQueryable.

On this article we are going to look at every of those interfaces and focus on how we are able to work with them in .NET 8, illustrated with code examples.

Create a console software challenge in Visible Studio

First off, let’s create a .NET Core console software challenge in Visible Studio. Assuming Visible Studio 2022 is put in in your system, comply with the steps outlined under to create a brand new .NET Core console software challenge.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new challenge.”
  3. Within the “Create new challenge” window, choose “Console App (.NET Core)” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new challenge” window, specify the title and site for the brand new challenge.
  6. Click on Subsequent.
  7. Within the “Extra data” window proven subsequent, select “.NET 8.0 (Lengthy Time period Help)” because the framework model you want to use.
  8. Click on Create.

We’ll use this .NET 8 console software challenge to work with the IEnumerable, ICollection, IList, and IQueryable interfaces within the subsequent sections of this text.

The IEnumerable interface in C#

The IEnumerable interface in C# means that you can iterate over a group of components. It incorporates one methodology referred to as GetEnumerator that returns an occasion of sort IEnumerable<T>. You should use this occasion to iterate a group of components in a read-only, forward-only method. You can not use IEnumerable to iterate backwards.

The IEnumerable<T> interface is outlined within the System.Collections namespace as proven under.

public interface IEnumerable<out T> : IEnumerable
{
    new IEnumerator<T> GetEnumerator();
}

The next code snippet illustrates how one can work with IEnumerable<T> in C#.

Checklist<string> cities = new Checklist<string>() { "New York", "London", "Tokyo", "Lisbon", "Hyderabad", "Chicago" };
IEnumerable<string> question = cities.The place(x => x.StartsWith("L"));
foreach (var metropolis in question)
{
    Console.WriteLine(metropolis);
}

If you execute the previous piece of code, the names of the cities that begin with the letter “L” can be displayed on the console window.

The ICollection interface in C#

The ICollection interface is the bottom interface of all lessons pertaining to the System.Collections namespace. It offers a generic assortment of objects the place the weather of the gathering are accessible utilizing an index.

The ICollection<T> interface is the generic equal of the ICollection interface. It extends the IEnumerable<T> interface, which in flip extends the IEnumerable interface as proven within the code snippet given under.

public interface ICollection<T> : IEnumerable<T>
{     
        int Rely { get; }
        bool IsReadOnly { get; }
        void Add(T merchandise);
        void Clear();
        bool Comprises(T merchandise);
        void CopyTo(T[] array, int arrayIndex);
        bool Take away(T merchandise);
}

In contrast to the IEnumerable interface, the ICollection interface means that you can add or take away components from a group. The next code snippet exhibits how you should utilize the ICollection interface in C#.

ICollection<string> international locations = new Assortment<string>();
international locations.Add("USA");
international locations.Add("India");
international locations.Add("England");
international locations.Add("Japan");
foreach (string nation in international locations)
{
    Console.WriteLine(nation);
}

If you execute the above code, the nation names added to the gathering can be displayed on the console window.

The IList interface in C#

The IList interface is on the market within the System.Collections namespace. It represents a strongly typed assortment wherein the weather of the gathering are accessible utilizing an index. IList extends the ICollection interface and incorporates extra strategies akin to IndexOf, Insert, and RemoveAt for working with collections.

The next code snippet exhibits how the IList<T> interface is outlined within the System.Collections namespace.

public interface IList : ICollection
    {
        Object this[int index] {
            get;
            set;
        }
        int Add(Object worth); 
        bool Comprises(Object worth);
        void Clear();
        bool IsReadOnly
        { get; }
         bool IsFixedSize
        {
            get;
        }
        int IndexOf(Object worth); 
        void Insert(int index, Object worth); 
        void Take away(Object worth); 
        void RemoveAt(int index);
    }

The code snippet under exhibits how one can create an occasion of sort IList and add and take away components to and from the gathering.

IList<string> prospects = new Checklist<string>();
prospects.Add("Joydip");
prospects.Add("Steve");
prospects.Add("Peter");
prospects.Insert(2, "Michael");
prospects.RemoveAt(0);
for (int i = 0; i < prospects.Rely; i++)
{
    Console.WriteLine(prospects[i]);
}

Be aware how a buyer title has been inserted to the gathering and the client title initially of the gathering has been deleted. If you execute the previous piece of code, the names current within the up to date assortment can be displayed on the console window as proven in Determine 1.

ilist in c sharp IDG

Determine 1. An IList instance in C#.

The IQueryable interface in C#

The IQueryable interface pertaining to the System.Linq namespace extends the IEnumerable interface and can be utilized to question knowledge from knowledge sources that implement IQueryable suppliers. The IQueryable<T>interface extends the IEnumerable<T> interface and is outlined as proven within the code snippet given under.

public interface IQueryable<out T> : IEnumerable<T>, IQueryable
{
}

Whereas the IEnumerable<T> interface can be utilized for working with in-memory collections of knowledge, the IQueryable<T> interface can be utilized with exterior knowledge sources akin to an internet service or a database. Take into account the next class.

public class Writer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public bool IsActive { get; set; }
}

The next code snippet demonstrates how one can work with the IQueryable interface in C#.

Checklist<Writer> authors = new Checklist<Writer>()
{
    new Writer(){Id = 1, FirstName = "Joydip", LastName = "Kanjilal", IsActive = true},
    new Writer(){Id = 2, FirstName = "Michael", LastName = "Smith", IsActive = false},
    new Writer(){Id = 3, FirstName = "Steve", LastName = "Jones", IsActive = true}
};
IQueryable<Writer> question = authors.AsQueryable()
                                 .The place(a => a.IsActive == true);
foreach (var creator in question)
{
    Console.WriteLine($"Id : {creator.Id}  FirstName : {creator.FirstName}    LastName : {creator.LastName}");
}

The IQueryable interface is acceptable for working with massive datasets, notably when it is advisable to implement paging to retrieve solely the info you want.

Which assortment interface must you use?

Right here’s a fast recap of the options of the IEnumerable, ICollection, IList, and IQueryable interfaces.

  • IEnumerable means that you can entry components of a group in a read-only, forward-only method. No including, deleting, or modifying the weather.
  • ICollection inherits from the IEnumerable interface and offers extra performance together with including, deleting, and modifying components.
  • IList extends the ICollection interface and represents strongly typed collections which can be accessible through index. So along with including, deleting, and modifying, you possibly can insert or take away gadgets utilizing index values.
  • IQueryable extends the IEnumerable interface, offers help for LINQ, and is well-suited for working with massive datasets. If you use IQueryable with LINQ to SQL or LINQ to Entities, it generates a LINQ to SQL expression that’s executed within the knowledge layer of your software.

The selection of assortment interface in C# will depend upon the necessities of your software. If you wish to question knowledge from a database, use IQueryable. If you wish to question knowledge from reminiscence, then use IEnumerable, ICollection, or IList, relying on what you wish to do with the weather of the gathering. 

Copyright © 2023 IDG Communications, Inc.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles