Wallatrixx
Wallatrixx

Reputation: 35

How To Read Data Into A List Structure in C#?

I am writing a program that uses a StudentStruct (structure) that consists of: studentID, studentName, and grades (which is a separate List). The program is supposed to read in a sequential text file and contains methods that allow the user to: Add Student, Add Grades (to a particular student), Change Student Name, and Delete Student. At the end of the program it is supposed to overwrite the previous file with the new changes made from the current program session.

My question is how do I read in data from the text file into the separate structure variables within the lists?

My text file looks like this:

00000,Mimzi Dagger,100,50,75,70,45,10,98,83
00001,Alexander Druaga,89,45,80,90,15,73,99,100,61
00002,Nicholas Zarcoffsky,100,50,80,50,75,100,100
00003,Kantmiss Evershot,50,100

Once the structure variables within the list are filled, how do I overwrite the file with the contents of the List structure in the same format as the above file?

Since I have multiple and varying amounts of grades, how would I achieve looping through and adding each grade to the grades list?

As you can maybe already tell, I am very new to c# and this is my first project. Any help would be greatly appreciated!

    class Program
    {
        static string pathSource = @"C:\schoolfiles\StudentGrades.txt";

        struct StudentStruct
        {
            public string studentID;
            public string studentName;
            public List<string> grades;
        }

        static void Main(string[] args)
        {
            StudentStruct student = new StudentStruct();
            List<StudentStruct> myList = new List<StudentStruct>();
            student.grades = new List<string>();
        }

UPDATE: Here is what I have come up with so far:

for (int i = 0; i < fileLines.Length; i++)
{
    output = fileLines[i];
    string[] outputArray = output.Split(',');

    student.grades = new List<string>();
    student.studentID = outputArray[0];
    student.studentName = outputArray[1];

    for (int j = 2; j < outputArray.Length; j++)
    {
        student.grades.Add(outputArray[j]);
    }

    myList.Add(student);

UPDATE: The code above worked out wonderfully. Here is the top part of my code involving this question:

static void Main(string[] args)
    {
        //Declare variables
        string output;

        //Read the File into an array
        string[] fileLines = File.ReadAllLines(PathSource);

        StudentStruct student = new StudentStruct();
        List<StudentStruct> myList = new List<StudentStruct>();



        for (int i = 0; i < fileLines.Length; i++)
        {
            output = fileLines[i];
            string[] outputArray = output.Split(',');

            student.grades = new List<string>();
            student.studentID = outputArray[0];
            student.studentName = outputArray[1];

            for (int j = 2; j < outputArray.Length; j++)
            {
                student.grades.Add(outputArray[j]);
            }

            myList.Add(student);
        }

        MainMenu(myList);
    }

And then to add the list back to the file I did this:

static void ExitModule(List<StudentStruct> myList)
    {
        //Declare variables
        string inputChoice = null;
        string output = null;

        System.IO.StreamWriter file = new System.IO.StreamWriter(PathSource);

        Console.Clear();
        Console.WriteLine("Are You Sure You Want To Exit The Program? Y/N");
        inputChoice = Console.ReadLine();

        if (inputChoice == "Y" || inputChoice == "y")
        {
            for (int i = 0; i < myList.Count; i++)
            {
                output = (myList[i].studentID + "," + myList[i].studentName);

                for (int j = 0; j < myList[i].grades.Count; j++)
                {
                    output += ("," + myList[i].grades[j]);
                }

                file.WriteLine(output);
            }

            file.Close();
            Environment.Exit(0);

Upvotes: 0

Views: 2226

Answers (3)

Dominic Williams
Dominic Williams

Reputation: 201

A few things.

(1) I am not sure why your teacher/professor would have you use a struct here. A class is much more appropriate. I actually cringed when I first saw the code

(2) having something as a const also implies that it is static "pathSource"

(3) Properties should be capitalized "pathSource" -> "PathSource"

(4) You should separate responsibilities... Try not to put everything in Main

(5) You shouldn't have to create an instance of grades outside of StudentStruct, this can lead to errors. i.e. NullPointerException... basically the struct should be self containing.

(6) Everything should compile. I haven't tested it. If you have any issues. let me know.

Program {
    private const string PathSource = @"C:\schoolfiles\StudentGrades.txt";

    private struct StudentStruct
    {
        public string StudentID;
        public string StudentName;

        private List<string> _gradeList;

        public List<string> GradeList
        {
            // if _gradeList is null create a new instance
            get { return _gradeList ?? (_gradeList = new List<string>()); }
            private set { _gradeList = value; }
        }
    }

    private static void Main( string[] args )
    {
        var studentFile = File.ReadAllLines( PathSource );
        // If you haven't learned about delegates or extensions methods...
        // You can just change it to a foreach statement
        var myList = studentFile.Select( GetStudent ).ToList();

        // make sure we have everything
        foreach (var studentStruct in myList)
        {
            Console.WriteLine( "{0}  {1}", studentStruct.studentName, studentStruct.studentID );
            foreach (var grade in studentStruct.GradeList) { Console.Write( grade + " " ); }
            Console.WriteLine();
        }
    }

    private static StudentStruct GetStudent( string line )
    {
        var student = new StudentStruct();
        var studentDelimited = line.Split( ',' );

        student.studentID = studentDelimited[ 0 ];
        student.studentName = studentDelimited[ 1 ];

        for ( int i = 2; i < studentDelimited.Length; i++ ) { student.GradeList.Add( studentDelimited[ i ] ); }

        return student;
    }
}

Upvotes: 0

Zohaib Aslam
Zohaib Aslam

Reputation: 595

try this code. it's working for me

class Program
    {
        static string pathSource = @"C:\schoolfiles\StudentGrades.txt";

        struct StudentStruct
        {
            public string studentID;
            public string studentName;
            public List<string> grades;
        }

        static void Main(string[] args)
        {
            StudentStruct student = new StudentStruct();
            List<StudentStruct> myList = new List<StudentStruct>();
            student.grades = new List<string>();

            // get all lines from text file
            string[] allLinesFromFile = File.ReadAllLines(pathSource);

            // iterate through each line and process it
            foreach(string line in allLinesFromFile)
            {
                // split each line on ','
                string[] sections = line.Split(',');
                student.studentID = sections[0];
                student.studentName = sections[1];

                // use this loop to add numbers to list of grades
                for(int i =2; i < sections.Length; i++)
                {
                    student.grades.Add(sections[i]);
                }

                // add this student to list
                myList.Add(student);

                // create new object of student
                student = new StudentStruct();
                student.grades = new List<string>();
            }
        }

Upvotes: 0

F.Buster
F.Buster

Reputation: 88

Since this is clearly homework, it may be a good time for you to learn about data structures. This will help you store the information you've read in from the text file efficiently, allowing you to write it out much more easily after modifying the records.

Here are a couple of other random pointers:

  • The System.IO.File.ReadLines(pathSource) method would be a good place to start reading each line of a text file
  • You should almost never be using a struct in C# (especially one that is mutable like in your example) unless you are well-versed in its semantics and purpose. Use a class instead

Upvotes: 2

Related Questions