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

王林
Release: 2023-09-03 14:57:04
forward
1553 people have browsed it

如何在 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();
}
Copy after login

Output

1
2
3
4
5
Copy after login

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

for IEnumerable

1
2
3
4
5
1
2
3
4
5
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template