在 C# 中将字符串数组转换为 Int 数组

您所在的位置:网站首页 js字符串数组转换为int数组 在 C# 中将字符串数组转换为 Int 数组

在 C# 中将字符串数组转换为 Int 数组

2024-06-27 15:11| 来源: 网络整理| 查看: 265

在 C# 中使用 Array.ConvertAll() 方法将字符串数组转换为 Int 数组 在 C# 中使用 LINQ 的 Select() 方法将字符串数组转换为 Int 数组

本指南将教我们在 C# 中将字符串数组转换为 int 数组。

有两种方法可以将 String 转换为 int。这两种方法都非常简单,也很容易实现。

在 C# 中使用 Array.ConvertAll() 方法将字符串数组转换为 Int 数组

每当我们谈论通过理解其内容将字符串转换为不同的数据类型时,都会涉及到解析。例如,字符串 321 可以转换为 321。

你可以使用的第一种方法是 Array.ConvertAll() 方法。让我们看看这个方法的实现。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Linq; namespace Array_of_String_to_integer { class Program { static void Main(string[] args) { // method 1 using Array.ConvertAll string[] temp_str = new string[] { "1000", "2000", "3000" }; int[] temp_int = Array.ConvertAll(temp_str, s => int.Parse(s)); for (int i = 0; i < temp_int.Length; i++) { Console.WriteLine(temp_int[i]); // Printing After Conversion............. } Console.ReadKey(); } } }

我们在上面的代码中使用了 Array.Convertall() 方法并传递数组。我们正在使用 int.Parse() 将字符串数组解析为一个 int 数组。

输出:

1000 2000 3000 在 C# 中使用 LINQ 的 Select() 方法将字符串数组转换为 Int 数组

我们可以使用 next 方法将字符串数组转换为 int 数组,方法是将 int.Parse() 方法传递给 LINQ 的 Select() 方法。我们还需要调用 ToArray() 方法来获取数组。

让我们看看实现。在此处了解有关 LINQ 的更多信息。

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Linq; namespace Array_of_String_to_integer { class Program { static void Main(string[] args) { Console.WriteLine("===================Using LINQ======================================="); // Method Using LINQ......................... // We can also pass the int.Parse() method to LINQ's Select() method and then call ToArray to // get an array. string[] temp_str = new string[] { "1000", "2000", "3000" }; int[] temp_int1 = temp_str.Select(int.Parse).ToArray(); for (int i = 0; i < temp_int1.Length; i++) { Console.WriteLine(temp_int1[i]); // Printing After Conversion............. } Console.ReadKey(); } } }

输出:

===================Using LINQ======================================= 1000 2000 3000


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3