This is one of the classes I have in C# :
public class Courses
{
[DataMember]
public string SchoolName { get; set; }
[DataMember]
public string MajorName { get; set; }
[DataMember]
public List<string> Course { get; set; }
public Courses()
{
Course = new List<string>();
}
}
For each Major, there is a list of classes.
In my database, I have three tables for school, major and courses joined with foreign leys. A simple SQL table to read them would be for a given school :
SELECT
major.MajorName,
course.CourseName
FROM school
INNER JOIN major ON major.MajorID = course.MajorID
WHERE school.SchoolName = @SchoolName AND major.SchoolNameID = school.SchoolNameID GROUP BY major.MajorName;
So based on this, I expect the data as follows. (Multiple major names and each major with multiple courses)
MajorName CourseName
Science SC101
Science SC102
Science SC500
Math MA100
Math MA200
ENGLISH EN450
What is the best way I could populate the class I derived at the beginning? My class definision inside database read query would be :
List<Courses> majorclasses = new List<Courses>()
I could manual manage the data to populate the class by reading distinct majorNames and then populating each course for each majorName in a loop.
(pheudo code)
List<string> distinctMajors = majorClasses.Disticnt("majorNames").ToList()
foreach major in distinctMajors
{
course.Add(courseName)
}
Any other better method to acheive this ?
You can try this.
List<Courses> courses = data.GroupBy(
d => new { d.SchoolName, d.MajorName},
d => d.CourseName,
(key,g) => new Courses {
MajorName = key.MajorName,
SchoolName = key.SchoolName,
Course = g.Distinct().ToList() }
).ToList();
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.