Search code examples
c#text-filesreadlinereadlines

Get an certain number of lines from a txt file in a list.


I have a problem. I'm making a tennis tournament program for a school project. We're supposed to use txt files, where they're being read an we need to be able to extract an certain amount of players, that is going to be used for simulation of the tournament.

public class ReadPlayers
{
    private List<ReadFiles> players = new List<ReadFiles>(); //Opretter en liste af strenge. 
    public string FileName { get; set; }
    public string Delimiter { get; set; }
    public ReadPlayers(string fn, string delim = "|") //Konstruktur
    {
        FileName = fn;
        Delimiter = delim;
    }

    public override string ToString()
    {
       var rv = "";

       foreach (var c in players)
             rv += c + "\n";
         return rv;
    }

    public void Load()
    {
        TextFieldParser par = new TextFieldParser(FileName, Encoding.GetEncoding("iso-8859-1"));
        par.TextFieldType = FieldType.Delimited;
        par.SetDelimiters(Delimiter);
        while (!par.EndOfData)
        {
            string[] fields = par.ReadFields();
            string FirstName = fields[1];
            string MiddleName = fields[2];
            string LastName = fields[3];
            DateTime DateOfBirth = DateTime.ParseExact(fields[4], "yyyy-MM-dd", CultureInfo.InvariantCulture);
            String Country = fields[5];
            string ShortNameCountry = fields[6];
            var c = new ReadFiles(FirstName, MiddleName, LastName, DateOfBirth, Country, ShortNameCountry);
            players.Add(c);
        }
        players.Shuffle();
        par.Close();

And in my main I load the file and print it. That works perfectly. But I need to be able to print only 8, 16, 32 or 64 players from the list.


Solution

  • There are ways to do it.

    1. Declare a constant(MAX_PLAYERS) or a variable to store the Max_Count of players you want i.e. 8, 16, 32 or 64. Declare a counter and increment it in the while loop. Once counter is reached exit from the loop. Here you will get only 1st 8 or 16 players form file which you are interested in. Not required to read full file when all records are not interested.

    while (!par.EndOfData && counter < MAX_PLAYERS)

    1. You have used the statement players.Shuffle();. So just pick the top MAX_PLAYERS from the list after shuffling. This makes more logical as you retain the full list of players and also the selected list out of them.

    var selectedList = players.Take(MAX_PLAYERS);