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

How Can I Efficiently Convert a String Array to an Integer Array Using LINQ?

DDD
Release: 2025-01-09 11:42:42
Original
840 people have browsed it

How Can I Efficiently Convert a String Array to an Integer Array Using LINQ?

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

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

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

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template