簡體   English   中英

從文本文件讀取整數

[英]Reading integers from text files

我有一個文件“ 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[] orderedNumbers = File.ReadLines(path)
    .Select(line => line.Trim().TryGetInt())
    .Where(nullableInteger => nullableInteger.HasValue)
    .Select(nullableInteger => nullableInteger.Value)
    .OrderByDescending(integer => integer)
    .ToArray();

這是我用來檢測字符串是否可以解析為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM