Many times there is need to
loop through collection of classes or List which are anonymous types,
IEnumerable interface is one of the best feature of C# language which
loop over the collection, let us learn about it step by step so
beginners also can understand.
What is IEnumerable interface ?
IEnumerable
is an interface that defines one method GetEnumerator which returns an
IEnumerator interface, this allows readonly access to a collection then
collection that implements IEnumerable can be used with a for-each
statement.
Key Points
- IEnumerable interface contains in the System.Collections.Generic namespace.
- IEnumerable interface is generic interface which allows to looping over generic or non-generic list.
- IEnumerable interface also works with linq query expression.
- IEnumerable interface Returns an enumerator that iterates through the collection.
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 element from the collection.
Methods of IEnumerator Interface
IEnumerator is an interface which helps to get current element from the collection,its has following two methods
- MoveNext()
- Reset()
Sets
the enumerator to the next element of the collection, it Returns true
if the enumerator was successfully sets to the next element and false if
the enumerator has passed 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 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(); } }
IEnumerable vs IEnumerator interface
While reading these two names, it's too confusion happen in mind 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 wants to implement enumerator logic in any of collection class, it need to be implement IEnumerable interface (either generic or non-generic).
- IEnumerable has just one method where as IEnumerator has two methods (MoveNext and Reset) and a property Current.
Let us learn it practically by creating one simple application as
Now create the project as:
In the above example 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
- "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 the 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 = 8888888888, Amount =426.00 }, new Customer { Name = "Anil", City = "Delhi", Mobile = 7777777777, 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 to loop through above collection as
public IEnumerable<Customer> GetAllCustomer() { return customers; }
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 iterating on each item contained in the GetAllCustomer() collection IEnumerable interface method, now whole code will be look like as follows
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 = 8888888888, Amount =426.00 }, new Customer { Name = "Anil", City = "Delhi", Mobile = 7777777777, Amount = 5896.20 } }; public IEnumerable<Customer> GetAllCustomer() { return customers; } } }
Now run the application and click on GetList button 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.
Summary
I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.
Post a Comment