在 C# 中将字符串数组转换为 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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。