简体   繁体   English

如何使用 MySQL 数据填充包含每个类项的类列表的类列表?

[英]How do I populate the class list which has list of classes for each class item with MySQL data?

This is one of the classes I have in C# :这是我在 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.在我的数据库中,我有三个表,分别是学校、专业和课程,并与外国 leys 相连。 A simple SQL table to read them would be for a given school :一个简单的 SQL 表来读取它们将用于给定的学校:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM