Languages
[Edit]
EN

C# / .NET - create new IEnumerable object from existing List

7 points
Created by:
Marcino
720

In this article, we would like to show you how to create new IEnumerable object from existing List in C#.

Practical example:

using System;
using System.Collections;
using System.Collections.Generic;

class EnumerableCollection<T> : IEnumerable<T>
{
    private IEnumerable<T> collection;

    public EnumerableCollection(IEnumerable<T> collection)
    {
        this.collection = collection;
    }

    public IEnumerator<T> GetEnumerator()
    {
        return this.collection.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.collection.GetEnumerator();
    }
}

public class Program
{
    public static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        IEnumerable<int> enumerable = new EnumerableCollection<int>(list);

        foreach (int i in enumerable)
            Console.WriteLine(i);
    }
}

Output:

1
2
3

References

  1. IEnumerable Interface (System.Collections) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join