C# IEnumerable vs IEnumerator

IEnumerable vs. IEnumerator 

IEnumerable vs. IEnumerator Both are uses to loop through lists. 
'For each' uses internally getEnumerator() to iterating to objects. 

Differences:- IEnumerable uses IEnumerator internally. 
IEnumerable does not remember its cursor position where as IEnumerator remembers it. 

For example you are writing two functions to list some details , one should list the years less than 2000 and other function should show the years greater than 2000. 

I Enumerator will support it by keeping its current cursor position (current state). 

 Example:- List Year = new List(); 

Year.Add(2000); 
Year.Add(2001); 
Year.Add(2002); 
IEnumerable getYear = (IEnumerable)Year; 
foreach (int i in getYear) { txtYeas.Text += i.ToString() + ","; } 
IEnumerator getsYear = Year.GetEnumerator(); 
while (getsYear.MoveNext()) { txtYeas.Text += getsYear.Current.ToString() + ","; } 

IComparable vs. IComparer Uses to sort algorithm in Array list of Custom Type. (For Example Employee Collection). You can sort strings based on alphabetical order, integer based on sequential order but if you want to sort a custom collection you need to use IComparable and IComparer with your custom logics.

IEnumerable vs. IQueryable vs. IList IEnumerable is the base interface, IList and IQueryable is implemented IEnumeable, means Both IList and IQueryable cqan do whatever IEnumeable interface can with their own functions as well. 


When to use: IEnumerable:When you use inproc memory object collections IQueryable: When you use ad hoc queries against datasource like Sql Server, Entity Framework IList: Add remove or refer an item by Index

Comments

Post a Comment

Popular posts from this blog

Performance Optimization in Sitecore

Strategies for Migrating to Sitecore from legacy or upgrading from older Sitecore

Azure Event Grid Sample code