如何在 C# 中将枚举转换为列表

Minahil Noor 2024年2月16日
如何在 C# 中将枚举转换为列表

本文将介绍如何在 C# 中把一个枚举 IEnumerable 转换为列表的方法。

  • 使用 ToList() 方法

在 C# 中使用 ToList() 方法将枚举类型转换为列表

在 C# 中,我们可以使用 Linq 类的 ToList() 方法将枚举转换为列表。使用该方法的正确语法如下所示

Enumerable.ToList(source);

方法 ToList() 只有一个参数。它的详细参数如下。

参数 说明
source 强制 这是我们要转换为列表的 IEnumerable

这个函数返回一个代表给定 IEnumerable 元素的列表。

下面的程序显示了我们如何使用 ToList() 方法将一个 IEnumerable 转换为列表。

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

class StringToByteArray {
  static void Main(string[] args) {
    IEnumerable<int> enumerable = Enumerable.Range(1, 50);
    List<int> mylist = enumerable.ToList();
    Console.WriteLine("The List is:");
    foreach (int length in mylist) {
      Console.WriteLine(length);
    }
  }
}

输出:

The List is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

相关文章 - Csharp IEnumerable

相关文章 - Csharp List