More Collection Initialization

This was another homework assignment that was done for a course I was taking. The requirements are commented in the code for each assignment button. This was more collections, initialization the collections, and iterating thru the collections to display the data. I’m also playing around with encapsulating data in a collection and iterating thru the collection to display the data. You will also see the various classes and object I’m using for the list items. And I’m taking advantage of using a class library on this project for code portability. No live version for this program because there isn’t much to see. You can download the source-code and take a look for yourself.

SchoolInterface SchoolProjectTree

Default.aspx HTML Code File Contents

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="School.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="assignmentButton1" runat="server" OnClick="assignmentButton1_Click" Text="Assignment 1" />
        <br />
        <br />
        <asp:Button ID="assignmentButton2" runat="server" OnClick="assignmentButton2_Click" Text="Assignment 2" />
        <br />
        <br />
        <asp:Button ID="assignmentButton3" runat="server" OnClick="assignmentButton3_Click" Text="Assignment 3" />
        <br />
        <br />
        <asp:Label ID="resultLabel" runat="server"></asp:Label>
    </form>
</body>
</html>

As you can see here not much other than some assignment buttons and a result label.

Default.aspx Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SchoolClassLibrary;

namespace School
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void assignmentButton1_Click(object sender, EventArgs e)
        {
            /*
             * Create a List of Courses (add three example Courses ...
             * make up the details).  Each Course should have at least two
             * Students enrolled in them.  Use Object and Collection
             * Initializers.  Then, iterate through each Course and print
             * out the Course's details and the Students that are enrolled in
             * each Course.
             */

            List<Course> course = new List<Course>()
            {
                // First course using list and object initialization.
                new Course { CourseId = 1, Name = "Calculus", Students = new List<Student>{
                    new Student { StudentId = 1, Name = "Daniel"},
                    new Student { StudentId = 2, Name = "Sara"} }
                },

                // Second course using list and object initialization.
                new Course { CourseId = 2, Name = "Macro Econ", Students = new List<Student> {
                    new Student { StudentId = 3, Name = "Daniel"},
                    new Student { StudentId = 4, Name = "Sara"} }
                },

                // Third course using list and object initialization.
                new Course { CourseId = 3, Name = "Social Communication", Students = new List<Student> {
                    new Student { StudentId = 5, Name = "Sara"},
                    new Student { StudentId = 6, Name = "Daniel"} }
                }
            };

            // Displaying the results with the help of the HtmlDisplayResult class.
            HtmlDisplayResult assignmentOneResults = new HtmlDisplayResult(course);
            resultLabel.Text = assignmentOneResults.AssignmentOneDisplayResults();
        }

        protected void assignmentButton2_Click(object sender, EventArgs e)
        {
            /*
             * Create a Dictionary of Students (add three example Students
             * ... make up the details).  Use the StudentId as the
             * key.  Each student must be enrolled in two Courses.  Use
             * Object and Collection Initializers.  Then, iterate through
             * each student and print out to the web page each Student's
             * info and the Courses the Student is enrolled in.
             */

            // Creating the course and student objects.
            Course courseOne = new Course() { CourseId = 1, Name = "Physics 101" };
            Course courseTwo = new Course() { CourseId = 2, Name = "CIS 105" };
            Course courseThree = new Course() { CourseId = 3, Name = "Communication Basics" };

            Student studentOne = new Student() { StudentId = 1, Name = "Daniel" };
            Student studentTwo = new Student() { StudentId = 2, Name = "Sara" };
            Student studentThree = new Student() { StudentId = 3, Name = "Bob" };

            // Create the dictionary list that contains the students and the courses they are enrolled in.
            Dictionary<int, Student> students = new Dictionary<int, Student>()
            {
                { studentOne.StudentId, new Student { StudentId = studentOne.StudentId, Name = studentOne.Name, Courses = new List<Course>() { courseOne, courseThree } } },
                { studentTwo.StudentId, new Student { StudentId = studentTwo.StudentId, Name = studentTwo.Name, Courses = new List<Course>() { courseTwo, courseOne } } },
                { studentThree.StudentId, new Student { StudentId = studentThree.StudentId, Name = studentThree.Name, Courses = new List<Course>() { courseThree, courseTwo } } }
            };

            // Displaying the results with the help of the HtmlDisplayResult class.
            HtmlDisplayResult assignmentTwoResults = new HtmlDisplayResult(students);
            resultLabel.Text += assignmentTwoResults.AssignmentTwoDisplayResults();
        }

        protected void assignmentButton3_Click(object sender, EventArgs e)
        {
            /*
             * We need to keep track of each Student's grade (0 to 100) in a
             * particular Course.  This means at a minimum, you'll need to add
             * another class, and depending on your implementation, you will
             * probably need to modify the existing classes to accommodate this
             * new requirement.  Give each Student a grade in each Course they
             * are enrolled in (make up the data).  Then, for each student,
             * print out each Course they are enrolled in and their grade.
             */

            // Creating the student objects to be used.
            Course courseOne = new Course() { CourseId = 1, Name = "Physics 101" };
            Course courseTwo = new Course() { CourseId = 2, Name = "Micro Economics" };
            Course courseThree = new Course() { CourseId = 3, Name = "Social Communication" };

            // Creating the student objects and encapsulating the enrolled courses and grades.
            Student studentOne = new Student()
            {
                StudentId = 1,
                Name = "Daniel",
                Enrollments = new List<Enrollment>()
                { new Enrollment { Course = courseOne, Grade = 95 },
                  new Enrollment { Course = courseThree, Grade = 90} }
            };

            Student studentTwo = new Student()
            {
                StudentId = 2,
                Name = "Sara",
                Enrollments = new List<Enrollment>()
                { new Enrollment { Course = courseTwo, Grade = 98 },
                  new Enrollment { Course = courseThree, Grade = 95} }
            };

            // Creating a dictionary list to hold the student information.
            Dictionary<int, Student> students = new Dictionary<int, Student>()
            {
                { studentOne.StudentId, studentOne },
                { studentTwo.StudentId, studentTwo }
            };

            // Displaying the results with the help of the HtmlDisplayResult class.
            HtmlDisplayResult assignmentThreeResults = new HtmlDisplayResult(students);
            resultLabel.Text += assignmentThreeResults.AssignmentThreeDisplayResults();
        }
    }
}

Here you can see the assignment button click event methods. Each one performs something different. Mentioned earlier is the requirements for each
button are in the code comments. You will see the object properties in the other classes and the meanings as they’re listed below.

The first assigment button is simple. Create a Course object with a Student list, iterate thru, and display the results in some format.

The second assigment button I chose to create my Course and Student objects, add them to Dictionary list, iterate thru the list, and display the results.

The third assigment button the Course objects were created to be used in Student objects that are being initialized with the Student object properties.
Then the Student objects and their values were added to a Dictionary list. Then the list is iterated thru and the data displayed.

Course.cs Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

A simple class with the course properties for the ID, Name, and a list of Students with properties from the Student class.

Enrollment.cs Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SchoolClassLibrary
{
    public class Enrollment
    {
        public int Grade { get; set; }
        public Course Course { get; set; }
    }
}

Another simple class similar to the Course class. Just some properties for the grade and a Course property object from the Course class.

Student.cs Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SchoolClassLibrary
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }

        // This property can be removed since the Enrollment list is defined below. However
        // this has a dependency on one of the other assignment buttons.
        public List<Course> Courses { get; set; }

        // Property created for the third button assignment. This list will inherit
        // the property objects of the Enrollment class.
        public List<Enrollment> Enrollments { get; set; }
    }
}

The Student class holds properties for the student ID, Name, List of Courses with properties from the Course class, and a List of Enrollments with properties from the Enrollment class.

Student.cs Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SchoolClassLibrary
{
    public class HtmlDisplayResult
    {
        // Private properties
        //
        private List<Course> _course;
        private Dictionary<int, Student> _student;

        // Constructors
        //
        public HtmlDisplayResult (List<Course> course)
        {
            this._course = course;
        }

        public HtmlDisplayResult (Dictionary<int, Student> student)
        {
            this._student = student;
        }

        // Public methods
        //
        // Display method for the first assignment button.
        public string AssignmentOneDisplayResults()
        {
            // Variable to hold the string value of the data being worked on.
            string result = "";

            // Iterating thru the list, pulling out the data, and storing it in the string.
            foreach (Course courseItems in _course)
            {
                // Getting the course information.
                result += String.Format("Course: {0} - {1}</br>", courseItems.CourseId, courseItems.Name);

                // Getting the student information.
                foreach (Student students in courseItems.Students)
                    result += String.Format("&nbsp&nbsp Student: {0} - {1}</br>", students.StudentId, students.Name);
            }
            return result;
        }

        // Display method used for the second assignment button.
        public string AssignmentTwoDisplayResults()
        {
            // Variable to hold the string value of the data being worked on.
            string result = "";

            // Iterating thru the list, pulling out the data, and storing it in the string.
            foreach (KeyValuePair<int, Student> studentDetails in _student)
            {
                result += String.Format("Student {0} - {1}</br>", studentDetails.Key, studentDetails.Value.Name);

                // Now loop thru the student details to get the courses enrolled in.
                foreach (Course studentCourses in studentDetails.Value.Courses)
                    result += String.Format("&nbsp&nbsp Course: {0} {1}</br>", studentCourses.CourseId, studentCourses.Name);
            }
            return result;
        }

        public string AssignmentThreeDisplayResults()
        {
            // Variable to hold the string value of the data being worked on.
            string result = "";

            // Loop thru the dictionary list and pull out the information we need to display.
            foreach (KeyValuePair<int, Student> studentDetails in _student)
            {
                result += String.Format("Student: {0} {1}</br>", studentDetails.Value.StudentId, studentDetails.Value.Name);

                // Loop thru and get the enrolled courses and grades.
                foreach (Enrollment studentEnrollment in studentDetails.Value.Enrollments)
                    result += String.Format("&nbsp&nbspEnrolled In: {0} - Grade: {1}</br>", studentEnrollment.Course.Name, studentEnrollment.Grade);
            }
            return result;
        }
    }
}

The HtmlDisplayResult class just formats the information needed and sends it back in a format that can be displayed.
I’ve defined methods for each button click to use. Notice how the iteration takes place and the differences from a generic
list to a generic dictionary list. Then I’m using String.Format() to send the info back for display.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s