tags:

views:

192

answers:

3

i like to know how to retrieve the elements from the list without using foreach.Thanks

+5  A: 
var list = new List<int> { 1, 2, 3, 4, 5 };
for (int i = 0; i < list.Count(); i++)
{
    var element = list[i];
}

or

var list = new List<int> { 1, 2, 3, 4, 5 };
using (var enumerator = list.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
    }
}
cxfx
Don't forget to dispose the enumerator.
Eric Lippert
Thanks - updated
cxfx
+1  A: 

You say list, but you don't specify the List<T> class as this answer assumes (also, it might be added that that answer uses the Count() extension method. Since you know the type is of List<T> it's better to use the Count property).

If you are always working with the IList<T> interface implementation, then using a for loop that iterates an index and then accesses the indexer with that value will work fine.

However, if you are dealing with IEnumerable<T> implementations, that will not always work. Rather, you have to do the following:

// Get the IEnumerator<T> from the list.
IEnumerator<T> enumerator = list.GetEnumerable();

// Dispose if necessary.
using (enumerator as IDisposable)
{
    // Cycle while there are items.
    while (enumerator.MoveNext())
    {
        // Work with enumerator.Current here.
    }
}

This is how the compiler expands the foreach statement when it is compiled. Basically, since IEnumerable<T> implementations can implement IDisposable, it prepares for that eventuality by trying to cast to IDisposable. If it cannot, then the using statement just doesn't do anything on exit.

When using foreach on arrays, the compiler will expand to a loop which accesses the items by index (assuming you are working with an array instance directly), not the enumerator approach above.

casperOne
+1  A: 

If you're trying to avoid this type of loop:

 foreach(var item in list) {};

...then you can use Linq or Lambda expressions to search and retrieve from the list.

For example:

  using System.Linq;

  // ... with Lambda
  var ints = new List<int>(){1,2,3,4,5};
  var evenInts = ints.ForEach(i => i % 2 == 0);

  // with straight Linq-to-objects:
  var oddInts = from i in ints
      where i % 2 == 1
      select i;
David Makogon