[英]Converting a String Array into an Int Array in C#
我正在尝试创建一个排序系统,并且试图将一个相当长的字符串形式的整数列表转换为一个int数组,以便能够更轻松地对数组进行排序。 初始字符串数组是通过从文本文件中读取整数列表形成的。
这是当前代码的外观,我目前正在根据年份进行排序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Climate_Sorting_Application
{
public class Program
{
public static string[] monthArray = File.ReadAllLines("Month.txt");
public static string[] yearArrayPre = File.ReadAllLines("Year.txt");
public static string[] afArray = File.ReadAllLines("WS1_AF.txt");
public static string[] rainArray = File.ReadAllLines("WS1_Rain.txt");
public static string[] sunArray = File.ReadAllLines("WS1_Sun.txt");
public static string[] tmaxArray = File.ReadAllLines("WS1_TMax.txt");
public static string[] tminArray = File.ReadAllLines("WS1_TMin.txt");
public static string[] af2Array = File.ReadAllLines("WS2_Rain.txt");
public static string[] rain2Array = File.ReadAllLines("WS2_Rain.txt");
public static string[] sun2Array = File.ReadAllLines("WS2_Sun.txt");
public static string[] tmax2Array = File.ReadAllLines("WS2_TMax.txt");
public static string[] tmin2Array = File.ReadAllLines("WS2_TMin.txt");
public static string arrayToAnalyse;
static void Main(string[] args)
{
Console.WriteLine("Please Specify the Data to be Analysed");
Console.WriteLine("You must specify the Text File name (Do not include .txt");
arrayToAnalyse = Console.ReadLine();
Console.ReadLine();
}
private static void sortProcess()
{
}
}
}
有什么方法可以轻松转换为正确的数据类型? 还是在初始文件读取期间将其转换为int值数组的方法?
当然! LINQ确实可以使事情变得简单:
int[] someArray = File.ReadAllLines(filename).Select(int.Parse).ToArray();
这将运行通过int.Parse()
方法读取的每一行,然后将这些结果转换为数组。
ToCharArray? 字符只是内存中的一个整数。
或者,您可以在A for循环中读取字符串,然后执行int.parse(index)。
https://msdn.microsoft.com/zh-CN/library/2c7h58e5(v=vs.110).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.