How to loop through a collection that supports IEnumerable?

后端 未结 5 1404
不知归路
不知归路 2020-12-23 20:00

How to loop through a collection that supports IEnumerable?

相关标签:
5条回答
  • 2020-12-23 20:39

    or even a very classic old fashion method

    IEnumerable<string> collection = new List<string>() { "a", "b", "c" };
    
    for(int i = 0; i < collection.Count(); i++) 
    {
        string str1 = collection.ElementAt(i);
        // do your stuff   
    }
    

    maybe you would like this method also :-)

    0 讨论(0)
  • 2020-12-23 20:43

    A regular for each will do:

    foreach (var item in collection)
    {
        // do your stuff   
    }
    
    0 讨论(0)
  • 2020-12-23 20:44

    Along with the already suggested methods of using a foreach loop, I thought I'd also mention that any object that implements IEnumerable also provides an IEnumerator interface via the GetEnumerator method. Although this method is usually not necessary, this can be used for manually iterating over collections, and is particularly useful when writing your own extension methods for collections.

    IEnumerable<T> mySequence;
    using (var sequenceEnum = mySequence.GetEnumerator())
    {
        while (sequenceEnum.MoveNext())
        {
            // Do something with sequenceEnum.Current.
        }
    }
    

    A prime example is when you want to iterate over two sequences concurrently, which is not possible with a foreach loop.

    0 讨论(0)
  • 2020-12-23 20:54

    Maybe you forgot the await before returning your collection

    0 讨论(0)
  • 2020-12-23 20:59
    foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
    {
    
    }
    
    0 讨论(0)
提交回复
热议问题