简体   繁体   中英

How to print members of a class when one of the properties of the class is a list

I have a class in which one of the properties is a list:

public class Course
{
    public int CourseId { get; set; }
    public string Name { get; set; }
    public List<Student> Students { get; set; }
}

I want to print out, for each Course ID and Course Name , the list of students enrolled in the course.

I've got a way to print out the various CourseIds and Course Name , namely:

foreach (Course course in courses)
{
    resultLabel.Text += course.FormatDetailsForDisplay();

Where:

public string FormatDetailsForDisplay()
{
    return String.Format("Course ID: {0} - Name: {1} <br/>", this.CourseId, this.Name);
}

But I have no idea how to iterate through the students for each course and print their details.

Use ForEach :

courses.ForEach(FormatDetailsForDisplay);

public void FormatDetailsForDisplay(Course course)
{
   string f = String.Format("Course ID: {0} - Course Name: {1} ", course.CourseId, course.Name);
   foreach (var item in course.Students)
   {
     f += "Student Name:" + item.Name;
   }
     resultLabel.Text += f;
}

If you use a custom method to get a string to display, I would use a similar approach for each part.

public string FormatDetailsForDisplay()
{
    StringBuilder sb = new StringBuilder();
    sb.Append("Course ID: ").Append(this.CourseId);
    sb.Append(" - Name: ").Append(this.Name).Append(" - Students: {");
    sb.Append(this.Students[0].FormatDetailsForDisplay());
    for (int i = 1; i < this.Students.Count; i++)
    {
        sb.Append(", ").Append(this.Students[i].FormatDetailsForDisplay());
    }
    sb.Append("} <br/>");
    return sb.ToString();
}
// Update FormatDetailsForDisplay() for the Students class depending on how you built it
public class Student
{
    public string Name;
    public int Age;

    public string FormatDetailsForDisplay()
    {
        return String.Format("Name: {0} - Age: {1}", this.Name, this.Age);
    }
}

To keep is short and sweet, add an override ToString() to your Student class that returns the Student information very similar to how the FormatDetailsForDisplay() method displays the information about the Class . The override ToString would look like:

public override string ToString()
{
    // Add what ever properties you have
    // I just used ID and Name
    return String.Format("\tID: {0} - Name: {1}\r\n", ID, Name);
}

Now, in the FormatDetailsForDisplay() you can do something like:

public string FormatDetailsForDisplay()
{
    return String.Format("Course ID: {0} - Name: {1}\r\n{2}", 
                         this.CourseId, 
                         this.Name,
                         String.Join("", this.Students.Select(s => s)));
}

Put it all together and you have something like:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        Course course = new Course {
            CourseId = 123456,
            Name = "Math",
            Students = new List<Student>()
        };

        course.Students.Add(new Student() {
            ID = 11111,
            Name = "John Doe"
        });
        course.Students.Add(new Student() {
            ID = 22222,
            Name = "Jane Doe"
        });

        Console.WriteLine(course.FormatDetailsForDisplay());
    }
}

public class Course
{
    public int CourseId { get; set; }
    public string Name { get; set; }
    public List<Student> Students { get; set; }

    public string FormatDetailsForDisplay()
    {
        return String.Format("Course ID: {0} - Name: {1}\r\n{2}", 
                             this.CourseId, 
                             this.Name,
                             String.Join("", this.Students.Select(s => s)));
    }
}

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }

    public override string ToString()
    {
        return String.Format("\tID: {0} - Name: {1}\r\n", ID, Name);
    }
}

Results:

Course ID: 123456 - Name: Math
    ID: 11111 - Name: John Doe
    ID: 22222 - Name: Jane Doe

See working example here... https://dotnetfiddle.net/arFF4t

foreach (Course course in courses) 
{
  resultLabel.Text += course.FormatDetailsForDisplay();
  foreach(var student in course.Students)
   resultLabel.Text += "student:" + student.Name;
}

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