IEnumerable<T> Interface

Définition

Expose l’énumérateur, qui prend en charge une itération simple sur une collection d’un type spécifié.Exposes the enumerator, which supports a simple iteration over a collection of a specified type.

generic <typename T>
public interface class IEnumerable : System::Collections::IEnumerable
public interface IEnumerable<out T> : System.Collections.IEnumerable
type seq<'T> = interface
    interface IEnumerable
Public Interface IEnumerable(Of Out T)
Implements IEnumerable

Paramètres de type

T

Type des objets à énumérer.The type of objects to enumerate.

Dérivé
Implémente

Exemples

L’exemple suivant montre comment implémenter l’interface IEnumerable<T> et comment utiliser cette implémentation pour créer une requête LINQ.The following example demonstrates how to implement the IEnumerable<T> interface and how to use that implementation to create a LINQ query. Lorsque vous implémentez IEnumerable<T>, vous devez également implémenter IEnumerator<T> ou C# , pour uniquement, vous pouvez utiliser le mot clé yield .When you implement IEnumerable<T>, you must also implement IEnumerator<T> or, for C# only, you can use the yield keyword. L’implémentation de IEnumerator<T> nécessite également l’implémentation de IDisposable, ce que vous verrez dans cet exemple.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.Linq;

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

    public static void TestStreamReaderEnumerable()
    {
        // Check the memory before the iterator is used.
        long memoryBefore = GC.GetTotalMemory(true);
      IEnumerable<String> stringsFound;
        // Open a file with the StreamReaderEnumerable and check for a string.
      try {
         stringsFound =
               from line in new StreamReaderEnumerable(@"c:\temp\tempFile.txt")
               where line.Contains("string to search for")
               select line;
         Console.WriteLine("Found: " + stringsFound.Count());
      }
      catch (FileNotFoundException) {
         Console.WriteLine(@"This example requires a file named C:\temp\tempFile.txt.");
         return;
      }

        // 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;
      try {
         sr = File.OpenText("c:\\temp\\tempFile.txt");
      }
      catch (FileNotFoundException) {
         Console.WriteLine(@"This example requires a file named C:\temp\tempFile.txt.");
         return;
      }

        // 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;
            if (_sr != 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
Imports System.IO
Imports System.Collections
Imports System.Collections.Generic
Imports System.Linq

Public Module App
   ' Excercise the Iterator and show that it's more performant.
   Public Sub Main()
      TestStreamReaderEnumerable()
      Console.WriteLine("---")
      TestReadingFile()
   End Sub

   Public Sub TestStreamReaderEnumerable()
        ' Check the memory before the iterator is used.
        Dim memoryBefore As Long = GC.GetTotalMemory(true)
      Dim stringsFound As IEnumerable(Of String)
        ' Open a file with the StreamReaderEnumerable and check for a string.
      Try
         stringsFound =
               from line in new StreamReaderEnumerable("c:\temp\tempFile.txt")
               where line.Contains("string to search for")
               select line
         Console.WriteLine("Found: {0}", stringsFound.Count())
      Catch e As FileNotFoundException
         Console.WriteLine("This example requires a file named C:\temp\tempFile.txt.")
         Return
      End Try

        ' Check the memory after the iterator and output it to the console.
        Dim memoryAfter As Long = GC.GetTotalMemory(false)
        Console.WriteLine("Memory Used with Iterator = {1}{0} kb",
                        (memoryAfter - memoryBefore)\1000, vbTab)
   End Sub

   Public Sub TestReadingFile()
        Dim memoryBefore As Long = GC.GetTotalMemory(true)
      Dim sr As StreamReader
      Try
         sr = File.OpenText("c:\temp\tempFile.txt")
      Catch e As FileNotFoundException
         Console.WriteLine("This example requires a file named C:\temp\tempFile.txt.")
         Return
      End Try

        ' Add the file contents to a generic list of strings.
        Dim fileContents As New List(Of String)()
        Do While Not sr.EndOfStream
            fileContents.Add(sr.ReadLine())
      Loop

        ' Check for the string.
        Dim stringsFound =
            from line in fileContents
            where line.Contains("string to search for")
            select line

      sr.Close()
      Console.WriteLine("Found: {0}", stringsFound.Count())

        ' Check the memory after when the iterator is not used, and output it to the console.
        Dim memoryAfter As Long = GC.GetTotalMemory(False)
        Console.WriteLine("Memory Used without Iterator = {1}{0} kb",
                        (memoryAfter - memoryBefore)\1000, vbTab)
   End Sub
End Module

' A custom class that implements IEnumerable(T). When you implement IEnumerable(T), 
' you must also implement IEnumerable and IEnumerator(T).
Public Class StreamReaderEnumerable : Implements IEnumerable(Of String)
    Private _filePath As String
    
    Public Sub New(filePath As String)
        _filePath = filePath
    End Sub

    ' Must implement GetEnumerator, which returns a new StreamReaderEnumerator.
    Public Function GetEnumerator() As IEnumerator(Of String) _
          Implements IEnumerable(Of String).GetEnumerator
        Return New StreamReaderEnumerator(_filePath)
    End Function

    ' Must also implement IEnumerable.GetEnumerator, but implement as a private method.
    Private Function GetEnumerator1() As IEnumerator _
          Implements IEnumerable.GetEnumerator
        Return Me.GetEnumerator()
    End Function
End Class

' 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 : Implements IEnumerator(Of String)
    Private _sr As StreamReader
    
    Public Sub New(filePath As String)
        _sr = New StreamReader(filePath)
    End Sub

    Private _current As String

    ' Implement the IEnumerator(T).Current Publicly, but implement 
    ' IEnumerator.Current, which is also required, privately.
    Public ReadOnly Property Current As String _
          Implements IEnumerator(Of String).Current
        Get
            If _sr Is Nothing OrElse _current Is Nothing
                Throw New InvalidOperationException()
            End If

            Return _current
        End Get
    End Property

    Private ReadOnly Property Current1 As Object _
          Implements IEnumerator.Current
        Get
           Return Me.Current
        End Get
    End Property

    ' Implement MoveNext and Reset, which are required by IEnumerator.
    Public Function MoveNext() As Boolean _
          Implements IEnumerator.MoveNext
        _current = _sr.ReadLine()
        if _current Is Nothing Then Return False

        Return True
    End Function

    Public Sub Reset() _
          Implements IEnumerator.Reset
        _sr.DiscardBufferedData()
        _sr.BaseStream.Seek(0, SeekOrigin.Begin)
        _current = Nothing
    End Sub

    ' Implement IDisposable, which is also implemented by IEnumerator(T).
    Private disposedValue As Boolean = False
    Public Sub Dispose() _
          Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub

    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' Dispose of managed resources.
            End If

            _current = Nothing
            If _sr IsNot Nothing Then
               _sr.Close()
               _sr.Dispose()
            End If
        End If

        Me.disposedValue = True
    End Sub

    Protected Overrides Sub Finalize()
        Dispose(False)
    End Sub
End Class
' This example displays output similar to the following:
'       Found: 2
'       Memory Used With Iterator =     33kb
'       ---
'       Found: 2
'       Memory Used Without Iterator =  206kb

Pour obtenir C# un autre exemple qui montre comment implémenter l’interface IEnumerable<T>, consultez l' exemple génériques.For another C# example that demonstrates how to implement the IEnumerable<T> interface, see the Generics Sample. Cet exemple utilise le mot clé yield au lieu d’implémenter IEnumerator<T>.This sample uses the yield keyword instead of implementing IEnumerator<T>.

Remarques

IEnumerable<T> est l’interface de base pour les collections dans l’espace de noms System.Collections.Generic, par exemple List<T>, Dictionary<TKey,TValue> et Stack<T>, ainsi que d’autres collections génériques telles que ObservableCollection<T> et ConcurrentStack<T>.IEnumerable<T> is the base interface for collections in the System.Collections.Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>. Les collections qui implémentent IEnumerable<T> peuvent être énumérées à l’aide de l’instruction foreach.Collections that implement IEnumerable<T> can be enumerated by using the foreach statement.

Pour obtenir la version non générique de cette interface, consultez System.Collections.IEnumerable.For the non-generic version of this interface, see System.Collections.IEnumerable.

IEnumerable<T> contient une méthode unique que vous devez implémenter lors de l’implémentation de cette interface ; GetEnumerator, qui retourne un objet IEnumerator<T>.IEnumerable<T> contains a single method that you must implement when implementing this interface; GetEnumerator, which returns an IEnumerator<T> object. Le @no__t retourné-0 donne la possibilité d’itérer au sein de la collection en exposant une propriété Current.The returned IEnumerator<T> provides the ability to iterate through the collection by exposing a Current property.

Notes pour les responsables de l’implémentation

Pour rester compatible avec les méthodes qui itèrent des collections non génériques, IEnumerable<T> implémente IEnumerable.To remain compatible with methods that iterate non-generic collections, IEnumerable<T> implements IEnumerable. Cela permet de passer une collection générique à une méthode qui attend un objet IEnumerable.This allows a generic collection to be passed to a method that expects an IEnumerable object.

Méthodes

GetEnumerator()

Retourne un énumérateur qui itère au sein de la collection.Returns an enumerator that iterates through the collection.

Méthodes d’extension

CopyToDataTable<T>(IEnumerable<T>)

Retourne un DataTable qui contient des copies des objets DataRow, à partir d'un objet d'entrée IEnumerable<T> où le paramètre générique T est DataRow.Returns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

Copie les objets DataRow vers le DataTable spécifié, à partir d'un objet d'entrée IEnumerable<T> où le paramètre générique T est DataRow.Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

Copie les objets DataRow vers le DataTable spécifié, à partir d'un objet d'entrée IEnumerable<T> où le paramètre générique T est DataRow.Copies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable)

Effectue un cast des éléments d'un IEnumerable vers le type spécifié.Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filtre les éléments d'un IEnumerable en fonction du type spécifié.Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Active la parallélisation d'une requête.Enables parallelization of a query.

AsQueryable(IEnumerable)

Convertit un IEnumerable en IQueryable.Converts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>)

Retourne une collection d'éléments qui contient les ancêtres de chaque nœud de la collection source.Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName)

Retourne une collection d'éléments filtrée qui contient les ancêtres de chaque nœud de la collection source.Returns a filtered collection of elements that contains the ancestors of every node in the source collection. Seuls les éléments avec un XName correspondant sont inclus dans la collection.Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>)

Retourne une collection des nœuds descendants de chaque document et élément de la collection source.Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>)

Retourne une collection d'éléments qui contient les éléments descendants de tous les éléments et tous les documents de la collection source.Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName)

Retourne une collection d'éléments filtrée qui contient les éléments descendants de tous les éléments et tous les documents de la collection source.Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. Seuls les éléments avec un XName correspondant sont inclus dans la collection.Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>)

Retourne une collection des éléments enfants de chaque élément et document de la collection source.Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName)

Retourne une collection filtrée des éléments enfants de chaque élément et document de la collection source.Returns a filtered collection of the child elements of every element and document in the source collection. Seuls les éléments avec un XName correspondant sont inclus dans la collection.Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>)

Retourne une collection de nœuds qui contient tous les nœuds de la collection source, triés selon l'ordre des documents.Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>)

Retourne une collection des nœuds enfants de chaque document et élément de la collection source.Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>)

Supprime chaque nœud de la collection source de son nœud parent.Removes every node in the source collection from its parent node.

S’applique à

Voir aussi