How to convert IEnumerable to List and List back to IEnumerable in C#?

CsharpServer Side ProgrammingProgramming

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated.

This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.

List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace.

List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists.

Example 1

static void Main(string[] args) {
   List list = new List();
   IEnumerable enumerable = Enumerable.Range(1, 5);

   foreach (var item in enumerable) {
      list.Add(item);
   }
   foreach (var item in list) {
      Console.WriteLine(item);
   }
   Console.ReadLine();
}

Output

1
2
3
4
5

Example 2

convert List to IEnumerable

static void Main(string[] args) {
   List list = new List();
   IEnumerable enumerable = Enumerable.Range(1, 5);

   foreach (var item in enumerable) {
      list.Add(item);
   }
   foreach (var item in list) {
      Console.WriteLine(item);
   }
   IEnumerable enumerableAfterConversion= list.AsEnumerable();
   foreach (var item in enumerableAfterConversion) {
      Console.WriteLine(item);
   }
   Console.ReadLine();
}

Output

1
2
3
4
5
1
2
3
4
5
raja
Published on 25-Nov-2020 16:19:42
Advertisements