cat
cat

Reputation: 19

Is there a way to read a txt file into a list without using List<String>?

I am trying to read a .txt file into a list without using a List<string> type. I have created a separate class, called Club, that does all of the sorting. However, I am having difficulties actually reading in the .txt file.

string path = "C:\\Users\\Clubs-2019";

public List<Club> ReadClubsTxtFile()
{
    List<Club> outcome = new List<Club>();
    string[] text = File.ReadAllLines(path);
    outcome.Add(text);
    return outcome;
}

The line outcome.Add(text); shows an error as I am trying to send the wrong type to the list.

This is a sample of the text file:

Club Name Club Number Meeting Address Latitude Longitude Meeting Day Meeting Time Meeting End Time Alabaster-Pelham 4018 1000 1st St North Alabaster AL 35007 33.252414 -86.813044 Thursday 12:15 PM 1:15 PM Albertville 4019 860 Country Club Road Albertville AL 35951 34.296807 -86.198587 Tuesday 12:00 PM 1:00 PM Alexander City 29375 16 Broad St. Alexander City AL 35010 32.945387 -85.953948 Monday 12:00 PM 1:00 PM

The "Clubs" Class is shown below.

public Club(string name, ClubTypes type, long idNumber, RecurrableMeeting regularMeeting = null, RecurrableMeeting boardMeeting = null, List<IndividualMeeting> otherMeetings = null)
    {
        this.name = name;
        this.type = type;
        this.idNumber = idNumber;
        this.regularMeeting = regularMeeting;
        this.boardMeeting = boardMeeting;

        this.otherMeetings = otherMeetings;
        if (this.otherMeetings == null)
            this.otherMeetings = new List<IndividualMeeting>();
    }

Upvotes: 0

Views: 247

Answers (2)

Rufus L
Rufus L

Reputation: 37030

"The line "outcome.Add(text); " shows an error as I am trying to send the wrong type to the list."

The reason for this error is that you're trying to add a string[] to a list that contains Club. What we need is a method that will take a string and return a Club, and then we can call that method on each file line before adding to the list.

A common way to do this is to add a Parse method to the Club class that can create an instance of the class from a string.

A complete example could be provided if you shared some sample lines from the text file (typically these would map to properties of the class) and the definition of the Club class. However, here is a sample that you can hopefully apply to your specific situation.

First, example lines in a text file:

1,Ravens,10/10/2019,2
2,Lions,05/25/2019,5.7
3,Tigers,09/12/2018,6.2
4,Bears,11/05/2019,9.1
5,Wildcats,03/04/2017,4.8

And the definition of Club

public class Club
{
    public int Id {get; set;}
    public string Name {get; set;}
    public DateTime FoundedOn {get; set;}
    public double Score {get; set;}
}

As you can see, the lines in the text file map to properties of the Club class. Now we just need to add a static method to the Club class that returns an instance of the class based on a line of text from the file.

The idea is that we split the line on the comma character, convert each part to the correct data type for the property, set the properties, and return the class. We need to validate things like:

  • The line is not null
  • The line contains the correct number of parts
  • Each part is the correct datatype

In the case of a validation failure, we have some common choices:

  • Throw an exception
  • Return null
  • Return a partially populated class

In the sample below I'm returning null to indicate bad data, mostly because it makes parsing the file easier.

Here's the class with the Parse method added:

public class Club
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime FoundedOn { get; set; }
    public double Score { get; set; }

    public static Club Parse(string input)
    {            
        // Try to split the string on the comma and
        // validate the result is not null and has 4 parts
        var parts = input?.Split(',');
        if (parts?.Length != 4) return null;

        // Strongly typed variables to hold parsed values
        int id;
        string name = parts[1].Trim();
        DateTime founded;
        double score;

        // Validate the parts of the string
        if (!int.TryParse(parts[0], out id)) return null;
        if (name.Length == 0) return null;
        if (!DateTime.TryParse(parts[2], out founded)) return null;
        if (!double.TryParse(parts[3], out score)) return null;

        // Everything is ok, so return a Club instance with properties set
        return new Club {Id = id, Name = name, FoundedOn = founded, Score = score};
    }
}

Now that we have the parse method, we can create a List<Club> from the text file quite easily:

public static List<Club> ReadClubsTxtFile(string path)
{
    return File.ReadAllLines(path).Select(Club.Parse).ToList();
}

Upvotes: 6

Cetin Basoz
Cetin Basoz

Reputation: 23797

You could do something like this:

string path = "C:\\Users\\Clubs-2019";
public List<Club> ReadClubsTxtFile()
{
    return File.ReadAllLines(path)
               .Select( line => new Club {SomeProperty = line} )
               .ToList();
}

Upvotes: -2

Related Questions