Home >Backend Development >C++ >How Can I Convert a System.Array to a List in C#?

How Can I Convert a System.Array to a List in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-03 14:46:43365browse

How Can I Convert a System.Array to a List in C#?

Converting System.Array to List: Is It Possible?

The query expressed in the question, converting an Array of integers to a List using "OfType()", fails to work as intended. The error translates to "cannot convert Array of type 'System.Int32' to type 'List'".

Instead, there are several viable approaches to achieve this conversion:

Convert to List

int[] ints = new[] { 10, 20, 10, 34, 113 };
List<int> lst = ints.ToList();

Create a New List

List<int> lst = new List<int> { 10, 20, 10, 34, 113 };

Add Items One by One

List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);

Use Array Constructor

List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });

AddRange Method

var lst = new List<int>();
lst.AddRange(new int[] { 10, 20, 10, 34, 113 });

The above is the detailed content of How Can I Convert a System.Array to a List in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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