Background
Many times there is a need to loop through a collection of classes or lists which are anonymous types. IEnumerable interface is one of the best features of C# language which loops over the collection. Let us learn about it step by step so beginners also can understand.
What is IEnumerable in C#?
IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
Key Points
- IEnumerable interface contains the System.Collections.Generic namespace.
- IEnumerable interface is a generic interface which allows looping over generic or non-generic lists.
- IEnumerable interface also works with linq query expression.
- IEnumerable interface Returns an enumerator that iterates through the collection.
Let us implement the IEnumerable interface in a class as:
public class Customer : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
In the above example, you have seen that after implementing the IEnumerable Interface there is method called GetEnumerator along with interface IEnumerator which helps to get current elements from the collection.
Methods of IEnumerator Interface
IEnumerator is an interface which helps to get current elements from the collection, it has the following two methods
- MoveNext()
- Reset()
MoveNext()
Sets the enumerator to the next element of the collection; it Returns true if the enumerator was successfully set to the next element and false if the enumerator has reached the end of the collection.
Reset()
Sets the enumerator to its initial position, which is before the first element in the collection.
Properties of IEnumerator Interface
IEnumerator Interface has a property named Current which returns the current element in the collection.
Let us implement the IEnumerator Interface in class as:
public class Customer : IEnumerator
{
public object Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
throw new NotImplementedException();
}
public void Reset()
{
throw new NotImplementedException();
}
}
In the above class we have implemented the IEnumerator interface which shows the above two methods and one property as we have already explained.
IEnumerable vs IEnumerator interface
While reading these two names, it can be confusing, so let us understand the difference between these two.
- IEnumerable and IEnumerator are both interfaces.
- IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator.
- If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).
- IEnumerable has just one method whereas IEnumerator has two methods (MoveNext and Reset) and a property Current.
For our understanding, we can say that IEnumebale is a box that contains IEnumerator inside it.
Let us learn it practically by creating one simple application.
Now create the project as:
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
- Provide the Project name such as "IEnumerableInterface" or another as you wish and specify the location.
- Then right-click on Solution Explorer and select "Add New Item" then select Default.aspx page.
- Add One Button.
Now the Default.aspx source code will be as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="IEnumerableInterface.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="GetList" OnClick="Button1_Click" />
</form>
</body>
</html>
Now open the Default.aspx.cs class file and create class named Customer with properties as:
public class Customer
{
private String _Name, _City;
private long _Mobile;
private double _Amount;
public String Name
{
get { return _Name; }
set { _Name = value; }
}
public String City
{
get { return _City; }
set { _City = value; }
}
public long Mobile
{
get { return _Mobile; }
set { _Mobile = value; }
}
public double Amount
{
get { return _Amount; }
set { _Amount = value; }
}
}
In the above class file we have created properties of type string, long and double which later on we will use along with IEnumerable generic interface. Now create the Array of type customer class and assign the values to each property as:
Customer[] customers = new Customer[]
{
new Customer {Name="Vithal Wadje",City="Mumbai",Mobile=99999999999,Amount=89.45 },
new Customer { Name = "Sudhir Wadje", City = "Latur", Mobile = 88888888888888888888, Amount =426.00 },
new Customer { Name = "Anil", City = "Delhi", Mobile = 77777777777777777777, Amount = 5896.20 }
};
Now in the above, customer type array has different types of values we have assigned to the properties that we have created, now let us use the IEnumerable interface loop through above collection as:
public IEnumerable<Customer> GetAllCustomer()
{
return customers;
}
In the above example I have assigned the Customer class collection to the IEnumerable to loop through each element, now we have already explained that IEnumerable interface collection can be iterated with the help of foreach loop over the IEnumerable interface collection, now let iterate through each item using IEnumerable interface as
foreach (var cust in GetAllCustomer())
{
Response.Write("Name: "+cust.Name + "
<br> " +"City: " +cust.City + " <br> " +"Mobile "+cust.Mobile+"<br>
"+"Amount :" +cust.Amount.ToString("c") + "<br>"+"-----"+"<br>");
}
In the above code, we are iterating on each item contained in the GetAllCustomer() collection IEnumerable interface method, now the whole code will look like the following:
using System;
using System.Collections.Generic;
namespace IEnumerableInterface
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (var cust in GetAllCustomer())
{
Response.Write("Name: "+cust.Name + "<br> " +"City: " +cust.City + " <br> "
+"Mobile "+cust.Mobile+"<br> "+"Amount :" +cust.Amount.ToString("c") + "<br>"+"-----"+"<br>");
}
}
public class Customer
{
private String _Name, _City;
private long _Mobile;
private double _Amount;
public String Name
{
get { return _Name; }
set { _Name = value; }
}
public String City
{
get { return _City; }
set { _City = value; }
}
public long Mobile
{
get { return _Mobile; }
set { _Mobile = value; }
}
public double Amount
{
get { return _Amount; }
set { _Amount = value; }
}
}
Customer[] customers = new Customer[]
{
new Customer {Name="Vithal Wadje",City="Mumbai",Mobile=99999999999,Amount=89.45 },
new Customer { Name = "Sudhir Wadje", City = "Latur", Mobile = 88888888888888888888, Amount =426.00 },
new Customer { Name = "Anil", City = "Delhi", Mobile = 77777777777777777777, Amount = 5896.20 }
};
public IEnumerable<Customer> GetAllCustomer()
{
return customers;
}
}
}
Now run the application and click on GetList button and the output will be as follows:
Now from the above example, it's clear that we can iterate through generic as well as non-generic collection with the help IEnumerable interface.
Notes
- Download the Zip file from the attachment for the full source code of the application.
Summary
I hope this article is useful for all readers, if you have any suggestions then please contact me, even if you're a beginner.