开发者

How to retrieve the elements in list without using foreach loop in C#?

How can I retrieve the elements from a list without using a foreach loop开发者_如何学Python?


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;
    }
}


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.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜