LINQ-Based String to Integer Array Conversion
Need to transform a string array holding integer representations into a true integer array? LINQ offers streamlined solutions.
Here's an example:
<code class="language-csharp">string[] strArray = { "1", "2", "3", "4" };</code>
These LINQ methods efficiently convert strArray
to an integer array:
Method 1: Array.ConvertAll
This approach uses the Array.ConvertAll
method for a concise conversion:
<code class="language-csharp">int[] intArray = Array.ConvertAll(strArray, s => int.Parse(s));</code>
The lambda expression s => int.Parse(s)
applies int.Parse
to each string element, converting it to an integer.
Method 2: Select
and ToArray
Alternatively, leverage LINQ's Select
and ToArray
methods:
<code class="language-csharp">int[] intArray = strArray.Select(int.Parse).ToArray();</code>
Select
transforms each string into an integer, and ToArray
creates the final integer array. Both methods achieve the same result with equal efficiency. Choose the method that best suits your coding style.
The above is the detailed content of How Can I Efficiently Convert a String Array to an Integer Array Using LINQ?. For more information, please follow other related articles on the PHP Chinese website!