List, IEnumbrable , IEnumerator

Posted by Bhupentiwari under C# on 9/28/2012 | Points: 10 | Views : 1471 | Status : [Member] | Replies : 2
Hi frnds

Please refer below code and kindly tell me the difference of looping over list using foreach,IEnumbrable and IEnumerator

Why i should use IEnumbrable and IEnumerator if i can do with foreach in simple way

  List<string> weekObj = new List<string>();    

weekObj.Add("Sunday");
weekObj.Add("Monday");
weekObj.Add("Tuesday");
weekObj.Add("Wednesday");
weekObj.Add("Thrusday");
weekObj.Add("Friday");
weekObj.Add("Saturday");

foreach (string d in weekObj)
Response.Write(d.ToString());
Response.Write("<br>");

IEnumerable weekenum = (IEnumerable)weekObj;
foreach (string day in weekenum)
Response.Write(day.ToString());
Response.Write("<br>");


IEnumerator weekIterator = weekObj.GetEnumerator();
while (weekIterator.MoveNext())
Response.Write(weekIterator.Current.ToString());


Thanks n Regards
Bhupendra Tiwari



Responses

Posted by: Pgayath on: 9/28/2012 [Member] Starter | Points: 25

Up
0
Down
Bhupendra:

I see the advantage only from performance stand point.
Whereas the List has following advantages.

1. We can iterate the IEnumerable interface using possibly only FOR-EACH loop. But List can be iterated using several ways. List can also be indexed by an int index and adding/ removing elements at a particular index is also easy.

2. We can't randomly access an IEnumerable interface, whereas we can use integral index to access the List.

Thanks and Regards,
Gayathri P



Bhupentiwari, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Pgayath on: 9/28/2012 [Member] Starter | Points: 25

Up
0
Down
Also please have alook at this.

http://stackoverflow.com/questions/3628425/ienumerable-vs-list-what-to-use-how-do-they-work

Bhupentiwari, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response