C# 从文本文件中读取整数
我有一个文件“HighScores.txt”,其中包含以下数据C# 从文本文件中读取整数,c#,C#,我有一个文件“HighScores.txt”,其中包含以下数据 0 12 76 90 54 我想将这个文本文件添加到一个整数数组中,因为我想对它进行排序,我只是在循环每个项目并将其从字符串转换为int时遇到了问题 string path = "score.txt"; int[] HighScores; if (!File.Exists(path)) { TextWriter tw = new StreamWriter(path); tw.Close()
0
12
76
90
54
我想将这个文本文件添加到一个整数数组中,因为我想对它进行排序,我只是在循环每个项目并将其从字符串转换为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
}
您可以使用LINQ:
int[] highScores = File
.ReadAllText("score.txt")
.Split(' ')
.Select(int.Parse)
.ToArray();
您可以使用File.ReadLines+Linq:
这是我用来检测字符串是否可以解析为int的扩展方法:
先生,当我有一行文字Pankaj 1212 dc3e 12 45r 12时,您能为一个案例提出建议吗。上面提到的代码till split给出了int和numeric值的混合数组。如何仅提取数字?
int[] orderedNumbers = File.ReadLines(path)
.Select(line => line.Trim().TryGetInt())
.Where(nullableInteger => nullableInteger.HasValue)
.Select(nullableInteger => nullableInteger.Value)
.OrderByDescending(integer => integer)
.ToArray();
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}