Home >Backend Development >C++ >How Can I Convert a String Array to an Integer Array Using LINQ in C#?
Convert string array to integer array in C# using LINQ
In programming, it is often necessary to convert an array of strings representing integers into an actual array of integers. This task can be easily accomplished using LINQ, a powerful language extension for working with collections.
LINQ solution using Select
One way to convert an array of strings to an array of integers is to use the Select extension method. This extension method allows you to convert each element of the collection into a new element using a specified lambda expression. In this case, the lambda expression can be int.Parse(s)
, where s is the string element:
<code class="language-csharp">int[] myInts = arr.Select(int.Parse).ToArray();</code>
This line of code applies the int.Parse
method to each string element in the array, effectively converting it to an integer. The result is a collection of integers, which is then converted to an array using the ToArray
method.
Alternatives using Array.ConvertAll
Another way to solve this problem is to use the Array.ConvertAll
method. This method accepts an array and a lambda expression as arguments and returns a new array containing the result of applying the lambda expression to each element of the input array. In this case, the lambda expression can be int.Parse
:
<code class="language-csharp">int[] myInts = Array.ConvertAll(arr, int.Parse);</code>
Short version using Array.ConvertAll
Finally, a cleaner version of the Array.ConvertAll
solution can be achieved by omitting the lambda expression. This will result in shorter and simpler lines of code:
<code class="language-csharp">int[] myInts = Array.ConvertAll(arr, int.Parse);</code>
The above is the detailed content of How Can I Convert a String Array to an Integer Array Using LINQ in C#?. For more information, please follow other related articles on the PHP Chinese website!