none
array reading from txt file RRS feed

  • Question

  • Hey guys, I forgot how to read array of integers as a part of Object class parameter. I've got object class Student and I need to read grades... 

    class Student
        {
            string lastName { get; set; }
            int[] grades { get; set; }

        }

    using (StreamReader reader = new StreamReader(dataFile))
                {
                    string line = null;
                    while (null != (line = reader.ReadLine()))
                    {
                        string[] values = line.Split(',');
                        string lastName = values[0];
                        int[] grades = 

    Thursday, September 28, 2017 7:44 PM

Answers

  • As I understand, you can define the array at runtime

    int[].grades = new int[5] {1, 2, 3, 4, 5};
    int[].grades = new int[3] {1, 2, 3};

    To read array of unknown size, you can use for loop with Array.Length

    for (int i = 0; i < grades.Length; i++)
    {
    	Console.WriteLine(grades[i]);
    }


    Thanks, AT

    • Marked as answer by Oscarfx Thursday, September 28, 2017 9:18 PM
    Thursday, September 28, 2017 8:45 PM

All replies

  • you need to first define the size of array and fill values. Example:

    int[].grades = new int[2] {1, 2};

    once populated, you can retrieve values by

    grades[0];
    grades[1];

    where 0 and 1 are index positions.


    Thanks, AT

    Thursday, September 28, 2017 7:58 PM
  • If you're keeping this code, it might do you some good to parse the rows in your class constructor.
    Test the string while reading the file and pass good strings to you constructor.

    TEHIII

    Thursday, September 28, 2017 8:01 PM
  • but in that case I must know how much elements are going to be in my grades array. I need flexible array, cause one object might have 5 elements and another 3 or 4
    Thursday, September 28, 2017 8:24 PM
  • As I understand, you can define the array at runtime

    int[].grades = new int[5] {1, 2, 3, 4, 5};
    int[].grades = new int[3] {1, 2, 3};

    To read array of unknown size, you can use for loop with Array.Length

    for (int i = 0; i < grades.Length; i++)
    {
    	Console.WriteLine(grades[i]);
    }


    Thanks, AT

    • Marked as answer by Oscarfx Thursday, September 28, 2017 9:18 PM
    Thursday, September 28, 2017 8:45 PM
  • Thanks, mate
    Thursday, September 28, 2017 9:18 PM