C# 中将数组转换为列表

本教程将讨论在 C# 中将数组转换为列表的方法。

在 C# 中使用 Linq 中的 Array.ToList() 方法将数组转换为列表

Linq 或语言集成查询用于 C# 中的快速文本操作。Linq 中的 Array.ToList() 方法可以转换数组到列表。Array.ToList() 方法将调用数组转换为列表,并以列表数据结构返回结果。下面的代码示例向我们展示了如何在 C# 的 Linq 中使用 Array.ToList() 方法将数组转换为列表。

using System;
using System.Collections.Generic;
using System.Linq;
namespace convert_array_to_list
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 10, 12, 13 };
            List<int> lst = arr.ToList();
            foreach (var element in lst)
            {
                Console.WriteLine(element);
            }
        }
    }
}

输出:

10
12
13

在 C# 中使用 List.AddRange() 方法将数组转换为列表

使用 List.AddRange() 方法在 C# 的列表内插入值的范围。List.AddRange() 在调用列表内插入任何数据结构的元素。以下代码示例向我们展示了如何使用 C# 中的 List.AddRange() 函数将数组转换为列表。

using System;
using System.Collections.Generic;
using System.Linq;
namespace convert_array_to_list
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 10, 20, 30 };
            List<int> lst = new List<int>();
            lst.AddRange(arr);
            foreach (var element in arr)
            {
                Console.WriteLine(element);
            }
        }
    }
}

输出:

10
20
30