简体   繁体   中英

How would I make a string get a property? C#

I got this database witch would display the grade of a student based on what I would write in the code. For example:

id = "Robert"
classType = "mathGrades"

And here is my code

public string grades;

public string loadQuery(string id, string classType)
{
    students = jsonService.GetData(); // My Json reader gets data from my Json file
    string Class = "student." + classType; //I combine the scripts

    foreach (Student student in students)
    {
        if (student.name == id)//Check if we have a student by this name, if we do then get the grades for the class defined in "classType"  
        {
            grades = string.Join(", ", Class);//This is the part that I understand why it doesn't work, but I don't have an idea on how to replace it
        }
    }
    return grades;
}

This is the Student class:

public class Student
{
    public string name { get; set; }

    public List<int> mathGrades { get; set; }

    public override string ToString() => JsonSerializer.Serialize(this);
}

And this is the json file containing the data

 [
      {
        "name": "Test1",
        "mathGrades": [ 1, 2, 3 ]
      },
    
      {
        "name": "Test2",
        "mathGrades": [ 1, 2, 3 ]
      }
]

I would want my output to be something like "1, 2, 3" but I just get student.mathGrades. Which I understand why, I just don't know how to fix it. Thanks in advance !

You should change

 grades = string.Join(", ", Class);

to

grades = string.Join(", ", student.mathGrades);

The above answer explained your mistake. String.Join expects array of values. In your example

string.Join(", ", "student.mathGrades");

returns student.mathGrades

You are creating a string named Class and setting it equal to "student.mathGrades" .

In your loop, you are effectively saying grades = string.Join(", ", "student.mathGrades")

Since "student.mathGrades" is just a single string, there is no joining and it's just returned.

If you want to have grades return a list of grades you need to pull that list from somewhere. It would help to know what your student object looks like.

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