Export (0) Print
Expand All

IEnumerable<T>.GetEnumerator Method

Returns an enumerator that iterates through the collection.

Namespace:  System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

IEnumerator<T> GetEnumerator()

Return Value

Type: System.Collections.Generic.IEnumerator<T>
An enumerator that can be used to iterate through the collection.

The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property .You can use enumerators to read the data in a collection, but not to modify the collection.

Initially, the enumerator is positioned before the first element in the collection. At this position, Current is undefined. Therefore, you must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current.

Current returns the same object until MoveNext is called again as MoveNext sets Current to the next element.

If MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. When the enumerator is at this position, subsequent calls to MoveNext also return false. If the last call to MoveNext returned false, Current is undefined. You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.

An enumerator does not have exclusive access to the collection so an enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is invalidated and you may get unexpected results when a. Also, enumerating a collection is not a thread-safe procedure. To guarantee thread-safety, you should lock the collection during enumerator or implement synchronization on the collection.

Default implementations of collections in the System.Collections.Generic namespace aren't synchronized.

The following example demonstrates how to implement the IEnumerable<T> interface and uses that implementation to create a LINQ query. When you implement IEnumerable<T>, you must also implement IEnumerator<T> or, for C# only, you can use the yield (C# Reference) keyword. Implementing IEnumerator<T> also requires IDisposable to be implemented, which you will see in this example.

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Diagnostics;

public class App
{
    // Excercise the Iterator and show that it's more 
    // performant. 
    public static void Main()
    {
        TestStreamReaderEnumerable();
        TestReadingFile();
    }

    public static void TestStreamReaderEnumerable()
	{
		// Check the memory before the iterator is used. 
		long memoryBefore = GC.GetTotalMemory(true);

		// Open a file with the StreamReaderEnumerable and check for a string. 
        var stringsFound =
            from line in new StreamReaderEnumerable(@"c:\\temp\\tempFile.txt")
            where line.Contains("string to search for")
            select line;


        Console.WriteLine("Found: " + stringsFound.Count());

		// Check the memory after the iterator and output it to the console. 
		long memoryAfter = GC.GetTotalMemory(false);
		Console.WriteLine("Memory Used With Iterator = \t"
            + string.Format(((memoryAfter - memoryBefore) / 1000).ToString(), "n") + "kb");
	}

    public static void TestReadingFile()
	{
		long memoryBefore = GC.GetTotalMemory(true);
        StreamReader sr = File.OpenText("c:\\temp\\tempFile.txt");

        // Add the file contents to a generic list of strings.
		List<string> fileContents = new List<string>();
		while (!sr.EndOfStream) {
			fileContents.Add(sr.ReadLine());
		}

		// Check for the string. 
		var stringsFound = 
            from line in fileContents
            where line.Contains("string to search for")
            select line;

        sr.Close();
        Console.WriteLine("Found: " + stringsFound.Count());

		// Check the memory after when the iterator is not used, and output it to the console. 
		long memoryAfter = GC.GetTotalMemory(false);
		Console.WriteLine("Memory Used Without Iterator = \t" + 
            string.Format(((memoryAfter - memoryBefore) / 1000).ToString(), "n") + "kb");

	}
}

// A custom class that implements IEnumerable(T). When you implement IEnumerable(T),  
// you must also implement IEnumerable and IEnumerator(T). 
public class StreamReaderEnumerable : IEnumerable<string>
{

    private string _filePath;
    public StreamReaderEnumerable(string filePath)
    {
        _filePath = filePath;
    }


    // Must implement GetEnumerator, which returns a new StreamReaderEnumerator. 
    public IEnumerator<string> GetEnumerator()
    {
        return new StreamReaderEnumerator(_filePath);
    }

    // Must also implement IEnumerable.GetEnumerator, but implement as a private method. 
    private IEnumerator GetEnumerator1()
    {
        return this.GetEnumerator();
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator1();
    }

}

// When you implement IEnumerable(T), you must also implement IEnumerator(T),  
// which will walk through the contents of the file one line at a time. 
// Implementing IEnumerator(T) requires that you implement IEnumerator and IDisposable. 
public class StreamReaderEnumerator : IEnumerator<string>
{
    private StreamReader _sr;
    public StreamReaderEnumerator(string filePath)
    {
        _sr = new StreamReader(filePath);
    }

    private string _current;
    // Implement the IEnumerator(T).Current publicly, but implement  
    // IEnumerator.Current, which is also required, privately. 
    public string Current
    {

        get
        {
            if (_sr == null || _current == null)
            {
                throw new InvalidOperationException();
            }

            return _current;
        }
    }

    private object Current1
    {

        get { return this.Current; }
    }
    object IEnumerator.Current
    {
        get { return Current1; }
    }

    // Implement MoveNext and Reset, which are required by IEnumerator. 
    public bool MoveNext()
    {

        _current = _sr.ReadLine();
        if (_current == null)
            return false;
        return true;
    }

    public void Reset()
    {
        _sr.DiscardBufferedData();
        _sr.BaseStream.Seek(0, SeekOrigin.Begin);
        _current = null;
    }
    // Implement IDisposable, which is also implemented by IEnumerator(T). 
    private bool disposedValue = false;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposedValue)
        {
            if (disposing)
            {
                // Dispose of managed resources.
            }
            _current = null;
            _sr.Close();
            _sr.Dispose();
        }

        this.disposedValue = true;
    }

     ~StreamReaderEnumerator()
    {
        Dispose(false);
    }
    // This example displays output similar to the following: 
    //Found: 2 
    //Memory Used With Iterator =     33kb 
    //Found: 2 
    //Memory Used Without Iterator =  206kb
}

For another C# example that demonstrates how to implement the IEnumerable<T> interface, see the Generics Sample. This sample uses of the yield keyword instead of implementing IEnumerator<T>.

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft