Home  >  Article  >  Backend Development  >  How to convert IEnumerable to List and List back to IEnumerable in C#?

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

王林
王林forward
2023-09-03 14:57:041482browse

如何在 C# 中将 IEnumerable 转换为 List 以及将 List 转换回 IEnumerable?

IEnumerable is an interface that defines a single method GetEnumerator() that returns the IEnumerator interface. It is the basic interface for all enumerable, non-generic collections.

This applies to read-only access to collections that implement IEnumerable, which can be used with a foreach statement.

The List class represents a list of objects that can be accessed by index. It is located under the System.Collection.Generic namespace.

The List class can be used to create collections of different types, such as integers, strings, etc. The List class also provides methods for searching, sorting, and manipulating 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 Output

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();
}

for IEnumerable

1
2
3
4
5
1
2
3
4
5

The above is the detailed content of How to convert IEnumerable to List and List back to IEnumerable in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete