c#中的向量类结构,多维的

本文关键字:结构 向量 | 更新日期: 2023-09-27 18:02:21

我想在c#中初始化一个c++类型的多维向量作为类(教师),其中一个特定的教师(成员)可以教一个或几个科目,比如:

A老师教生物但老师B教生物和数学(等等)

我希望用户输入科目,这样用户就可以随心所欲地增加科目的数量,并且这个"列表"可以按照教师姓名的字母顺序排列。

这将是一个类结构,如果是,如何?

c#中的向量类结构,多维的

你似乎在要求多维数组,你可以在c#中声明,但这并没有利用类的功能:

var teachers = new string[2][];
teachers[0] = new [] {"Biology"};
teachers[1] = new[] { "Biology" , "Maths"};

最好是维护教师和科目的集合,然后使用Linq以所需的顺序返回教师-科目对。我将主题保持为字符串形式,但在实际情况中,您可能也希望将它们封装在类中。

void Main
{    
  School school = new School();
  school.Add("Harry", "Quiddich");
  school.Add("Ron", "Quiddich");
  school.Add("Neville", "Herbology");
  school.Add("Hermione", "Herbology");
  school.Add("Hermione", "Divination");
  var orderedTeachers =
       school.Teachers.OrderBy(t => t.TeacherName)
            .SelectMany(
                x => x.Subjects.OrderBy(s => s).Select(s => new {Teacher = x.TeacherName, Subject = s}));
}
internal class School
{
    internal List<string> TaughtSubjects { get; } = new List<string>();
    internal List<Teacher> Teachers { get; } = new List<Teacher>();
    internal void Add(string teacherName, string subjectName)
    {
        // check to see if we have alreay defined this subject
        var subject = TaughtSubjects.SingleOrDefault(s => s == subjectName);
        // else create the subject and add to the school curriculum
        if (subject == null)
        {
            subject = subjectName;
            TaughtSubjects.Add(subject);
        }
        // check to see if the teacher is already on the school payroll
        var teacher = Teachers.SingleOrDefault(s => s.TeacherName == teacherName);
        // if not then add him or her
        if (teacher == null)
        {
            teacher = new Teacher(teacherName);
            Teachers.Add(teacher);
        }
        // check that the teacher isn't already down for teaching that subject before making the link
        if (!teacher.Subjects.Contains(subject))
            teacher.Subjects.Add(subject);
    }
}
internal class Teacher
{
    internal Teacher(string teacherName)
    {
        TeacherName = teacherName;
    }
    internal string TeacherName { get; }
    public List<string> Subjects { get; } = new List<string>();
}