Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从文本文件中读取整数_C# - Fatal编程技术网

C# 从文本文件中读取整数

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()

我有一个文件“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();
    }
    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;
}