EN
C# / .NET - create new IEnumerable object from existing List
7 points
In this article, we would like to show you how to create new IEnumerable object from existing List in C#.
Practical example:
xxxxxxxxxx
1
using System;
2
using System.Collections;
3
using System.Collections.Generic;
4
5
class EnumerableCollection<T> : IEnumerable<T>
6
{
7
private IEnumerable<T> collection;
8
9
public EnumerableCollection(IEnumerable<T> collection)
10
{
11
this.collection = collection;
12
}
13
14
public IEnumerator<T> GetEnumerator()
15
{
16
return this.collection.GetEnumerator();
17
}
18
19
IEnumerator IEnumerable.GetEnumerator()
20
{
21
return this.collection.GetEnumerator();
22
}
23
}
24
25
public class Program
26
{
27
public static void Main()
28
{
29
List<int> list = new List<int> { 1, 2, 3 };
30
31
IEnumerable<int> enumerable = new EnumerableCollection<int>(list);
32
33
foreach (int i in enumerable)
34
Console.WriteLine(i);
35
}
36
}
Output:
xxxxxxxxxx
1
1
2
2
3
3