简体   繁体   中英

Reading integers from text files

I have a file 'HighScores.txt' which contains data such as

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.

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:

int[] highScores = File
    .ReadAllText("score.txt")
    .Split(' ')
    .Select(int.Parse)
    .ToArray();

You can use 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 :

public static int? TryGetInt(this string item)
{
    int i;
    bool success = int.TryParse(item, out i);
    return success ? (int?)i : (int?)null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM