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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-27 00:56:09160browse

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

Converting System.Array to List: A Practical Guide

Can System.Array be converted to List, a common question that has sparked both intrigue and debate over its feasibility? The answer, surprisingly, is a resounding yes.

To convert an array to a list, one might instinctively turn to OfType<>(). However, this approach is far from optimal, as demonstrated by the example below:

Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);
ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);

// List<int> lst = ints.OfType<int>(); // Not recommended

Save yourself the headache and opt for the following solutions instead:

int[] ints = { 10, 20, 10, 34, 113 };

// Using ToList()
List<int> lst = ints.OfType<int>().ToList();

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

// Initializing and adding elements
List<int> lst = new List<int>();
lst.Add(10);
lst.Add(20);
lst.Add(10);
lst.Add(34);
lst.Add(113);

// Initializing with an array
List<int> lst = new List<int>(new int[] { 10, 20, 10, 34, 113 });

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

These methods provide more efficient and straightforward ways to convert from System.Array to List. Choose the approach that best suits your needs, and happy coding!

The above is the detailed content of How Can I Efficiently 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