[英]Reading integers from text files
I have a file 'HighScores.txt' which contains data such as 我有一个文件“ HighScores.txt”,其中包含诸如
0
12
76
90
54
I would like to add this text file into an array of integers as I would like to sort this, I'm just having trouble looping through each item and converting it from a string to an int. 我想将此文本文件添加到整数数组中,就像我要对其进行排序一样,我只是在遍历每个项目并将其从字符串转换为int时遇到麻烦。
string path = "score.txt";
int[] HighScores;
if (!File.Exists(path))
{
TextWriter tw = new StreamWriter(path);
tw.Close();
}
else if (File.Exists(path))
{
//READ FROM TEXT FILE
}
You could use LINQ: 您可以使用LINQ:
int[] highScores = File
.ReadAllText("score.txt")
.Split(' ')
.Select(int.Parse)
.ToArray();
You can use File.ReadLines
+ Linq: 您可以使用
File.ReadLines
+ Linq:
int[] orderedNumbers = File.ReadLines(path)
.Select(line => line.Trim().TryGetInt())
.Where(nullableInteger => nullableInteger.HasValue)
.Select(nullableInteger => nullableInteger.Value)
.OrderByDescending(integer => integer)
.ToArray();
This is the extension method which i'm using to detect if a string can be parsed to an int
: 这是我用来检测字符串是否可以解析为
int
的扩展方法:
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.