Home >Backend Development >C++ >How Can I Efficiently Convert a String Array to an Integer Array in C#?

How Can I Efficiently Convert a String Array to an Integer Array in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-09 11:52:42359browse

How Can I Efficiently Convert a String Array to an Integer Array in C#?

A single line of LINQ in C# to achieve efficient string to integer conversion

Need to efficiently convert an array containing a string of integers into an array of actual integers? Simple type conversion doesn't work and manual looping is too cumbersome?

LINQ provides a simple and elegant solution. Leverage lambda expressions and query syntax to complete the conversion with minimal code:

<code class="language-csharp">int[] myInts = arr.Select(int.Parse).ToArray();</code>

In this LINQ expression, the Select method applies the int.Parse transformation to each element of the arr array, effectively parsing the string representation into an integer. Then, use ToArray() to convert the resulting enum to an array.

Example usage:

<code class="language-csharp">string[] arr = new string[] { "1", "2", "3", "4" };
int[] myInts = arr.Select(int.Parse).ToArray();</code>

This code generates an array named myInts containing the integers 1, 2, 3, and 4, which you can easily pass to methods that expect real integers.

Alternatives:

If performance is critical, you might consider using Array.ConvertAll, which may be slightly better than LINQ in some cases:

<code class="language-csharp">int[] myInts = Array.ConvertAll(arr, int.Parse);</code>

Simply replace the Select part in the LINQ expression with Array.ConvertAll to use this optimization.

By using LINQ's expressive power or Array.ConvertAll's performance advantages, you can easily convert an array of strings to an array of integers with a single line of code.

The above is the detailed content of How Can I Efficiently Convert a String Array to an Integer Array 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