IEnumerable:
- It contains only one method and the return type is IEnumerator
- The Method name is GetEnumerator
- Below is the Default Syntax
- IEnumerable doesn't maintain States (currently, it does not know which row is iterating )
- It is an Interface
- the list class resides in "using System.Collections.Generic"
- Syntax is shart
- Actually, IEnumerable uses the IEnumerator internally.
namespace System.Collections.Generic { public interface IEnumerable<out T> : IEnumerable { merator<T> GetEnumerator();
} } |
---|
IEnumerator:
- It contains 2 methods and one property
- IEmerator is an Interface
- It Maintains States (currently, it knows which row is iterating )
- it maintains the current property and MoveNext and Reset Method
- the list class resides in "using System.Collections.Generic"
- The syntax is not shart
using System.Runtime.InteropServices; namespace System.Collections { public interface IEnumerator
{ object Current { get; } bool MoveNext(); void Reset();
} |
---|
States:
- The Biggest Different between them is States, now I am showing below snippet
- IEnumerable doesn't maintain states
- IEnumerator maintain states
using System; using System.Collections.Generic; namespace ConsolePractice {
class Program
{
static void Main(string[] args)
{ List<int> list = new List<int>(); list.Add(995); list.Add(996); list.Add(997); list.Add(998); list.Add(999); list.Add(2000); list.Add(2001); list.Add(2002); list.Add(2003);
list.Add(2004); list.Add(2005); IEnumerator<int> ienumerator =list.GetEnumerator(); statemaintsin95to2000(ienumerator); Console.ReadLine();
}
static void
statemaintsin95to2000(IEnumerator<int> ienumerator)
{ Console.WriteLine("Before Iterating the
IEnumerator from 95 to 2000"); while (ienumerator.MoveNext()) { if (Convert.ToInt32(ienumerator.Current) >= 2000) {
statemaintsin2000to2005(ienumerator); } Console.WriteLine(ienumerator.Current.ToString()); }
}
static void
statemaintsin2000to2005(IEnumerator<int> ienumerator)
{ Console.WriteLine("After Iterating the IEnumerator
from 95 to 2000"); while (ienumerator.MoveNext()) { Console.WriteLine(ienumerator.Current.ToString()); }
}
} |
---|
using System; using System.Collections.Generic; namespace ConsolePractice {
class Program
{
static void Main(string[] args)
{ List<int> list = new List<int>(); list.Add(995); list.Add(996); list.Add(997); list.Add(998); list.Add(999); list.Add(2000); list.Add(2001); list.Add(2002); list.Add(2003);
//iterate by using the list Console.WriteLine("Iterating List"); foreach (int i in list) { Console.WriteLine(i); } //iterating the IEnumeraable Console.WriteLine("Iterating the IEnumerable"); IEnumerable<int> ienumerable = (IEnumerable<int>)list; foreach (int i in ienumerable) { Console.WriteLine(i); } //iterating the ienumerator Console.WriteLine("Iterating the IEnumerator"); IEnumerator<int> ienumerator = list.GetEnumerator(); { Console.WriteLine(ienumerator.Current.ToString()); }
}
} |
---|
Post a Comment (0)