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
Release: 2025-01-03 14:46:43
Original
405 people have browsed it

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

Create a New List

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

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

Use Array Constructor

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

AddRange Method

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

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 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template