【问题标题】:working with lists in c# - without using database - many to many在 C# 中使用列表 - 不使用数据库 - 多对多
【发布时间】:2020-05-20 16:43:11
【问题描述】:

我已经看过How to model a Many to many-relationship in code?

我不太明白答案。

也看过C# Mapping Many To Many,但不想使用实体框架/数据库

我有学生和科目

public class Subject : Student
    {
        public string SubjectName { get; set; }
        public string StudentClassNumber { get; set; }
    }

    public class Student
    {
        public string StudentName { get; set; }
        public string isjoined { get; set; }


    }

然后实例化

List<Subject> subject = new List<Subject>();

并添加值/属性

subject2.Add(new Subject2() { SubjectName = "Math", StudentName = "Ben", isjoined = "yes", StudentClassNumber ="2" });
            subject2.Add(new Subject2() { SubjectName = "Math", StudentName2 = "Andrew", isjoined = "yes", StudentClassNumber = "4" });
            subject2.Add(new Subject2() { SubjectName = "Science", StudentName2 = "Andrew", isjoined = "no", StudentClassNumber = "5" });
            subject2.Add(new Subject2() { SubjectName = "Science", StudentName2 = "Ben", isjoined = "no", StudentClassNumber = "3" });

现在我的问题是,“数学”中的“安德鲁”或“本”与“科学”中的(学生)相同,这不是新的安德鲁和本

我想有一个 WriteLine 写:Math - StudentName - StudentClassNumber - 已加入, 两个/所有学生

即数学: 本 2 是的 安德鲁 4 是的

科学 本 3 没有 安德鲁 4 没有

这是使用 linq 的尝试

class Students
    {
        public string StudentName { get; set; }

    }

    class Subject
    {
        public string Name { get; set; }
        public Students Occupier { get; set; }
    }

    class InnerJoin3
    {
        public static void DoJoin()
        {
            Students ben = new Students { StudentName = "Ben" };
            Students andrew = new Students { StudentName = "Andrew" };


            Subject math = new Subject { Name = "Math", Occupier = andrew };
            Subject science = new Subject { Name = "Science", Occupier = ben };

            // Create two lists.
            List<Students> people = new List<Students> { ben, andrew };
            List<Subject> subjects = new List<Subject> { math, science };

            // Create a collection of student-subject pairs. Each element in the collection
            // is an anonymous type containing both the student's name and their subject's name.
            var query = from student in people
                        join subject in subjects on student equals subject.Occupier
                        select new { OccupierName = student.StudentName, SubjectName = subject.Name };

            foreach (var ownerAndSubject in query)
            {
                Console.WriteLine($"\"{ownerAndSubject.SubjectName}\" is the subject of choice for {ownerAndSubject.OccupierName}");
            }
        }
    }

【问题讨论】:

  • 为什么Subject继承自Student?当然,学科不是学生,学科也不是特定类型的学生。
  • 你的方法在这里都是错误的。学生和科目无关。我认为您需要一个额外的对象来帮助您将它们联系在一起,例如教室。一个教室可以有一个科目和多个学生。
  • 不幸的是,这是对我的问题的类比,所以保持类比,我的问题可能有一个教室,但教室会有多个科目
  • Subject2() 来自哪里?

标签: c#


【解决方案1】:

好吧,如果它像你说的那样。您希望在控制台应用程序中获得以下结果:

Math: name, name
Science: name.. etc.

在您的主类中添加以下内容:

static void Main(string[] args)
        {
            Students ben = new Students { StudentName = "Ben" };
            Students andrew = new Students { StudentName = "Andrew" };


            Subject mathAndrew = new Subject { Name = "Math", Students = andrew };
            Subject ScienceAndrew = new Subject { Name = "Science", Students = andrew };
            Subject scienceBen = new Subject { Name = "Science", Students = ben };

            List<Students> people = new List<Students> { ben, andrew };
            List<Subject> subjects = new List<Subject> { mathAndrew, ScienceAndrew, scienceBen };

            var query = from student in people
                        join subject in subjects on student equals subject.Students
                        select new SetQuery(student.StudentName, subject.Name);

            ScienceResult(query);
        }

并添加此方法:

注意,为了创建 ScienceResult 方法,我们需要一个 SetQuery 类实例。

public static void ScienceResult(IEnumerable<SetQuery> query)
        {
            Console.Write("Science: ");
            foreach (var result in query)
            {
                if (result.Name == "Science")
                {
                    Console.Write(result.StudentName + " ");
                }
            }

            Console.WriteLine();

            Console.Write("Math: ");
            foreach (var result in query)
            {
                if (result.Name == "Math")
                {
                    Console.Write(result.StudentName + " ");
                }
            }

            Console.WriteLine();
        }

使用依赖注入设置查询类实例

internal class SetQuery
    {
        public string StudentName;
        public string Name;

        public SetQuery(string studentName, string name)
        {
            this.StudentName = studentName;
            this.Name = name;
        }
    }

结果是:

Science: Ben Andrew
Math: Andrew

对于最佳实践,我会使用数据库保存您的信息并GET您的信息来自。此外,方法 ScienceResultNOT DRY 你想要改变。这仅用于说明目的

有关 DRY 的更多信息,请查看以下内容: DRY (Don't Repeat Yourself) and if assignements

【讨论】:

    【解决方案2】:

    不确定您到底在寻找什么,但最好的软件实践是该死的,给您(假设解决方案称为“stackoverflow61918396”):

    Student.cs

    using System.Collections.Generic;
    
    namespace stackoverflow61918396
    {
        class Student
        {
            public string Id { get; set; }
    
            public string Name { get; set; }
    
            public List<string> SubjectsEnrolledIn { get; set; }
    
            public Student()
            {
                SubjectsEnrolledIn = new List<string>();
            }
        }
    }
    

    Subject.cs

    using System.Collections.Generic;
    
    namespace stackoverflow61918396
    {
        class Subject
        {
            public string Id { get; set; }
    
            public int ClassNumber { get; set; }
    
            public string Name { get; set; }
    
            public List<string> StudentsInSubject { get; set; }
    
            public Subject()
            {
                StudentsInSubject = new List<string>();
            }
        }
    }
    

    Manager.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace stackoverflow61918396
    {
        class Manager
        {
            public static List<Student> Students { get; set; }
    
            public static List<Subject> Subjects { get; set; }
    
            public Manager()
            {
                Students = new List<Student>();
                Subjects = new List<Subject>();
    
                // Seed some students
                var ben = new Student() { Id = Guid.NewGuid().ToString(), Name = "Ben" };
                var andrew = new Student() { Id = Guid.NewGuid().ToString(), Name = "Andrew" };
                var amanda = new Student() { Id = Guid.NewGuid().ToString(), Name = "Amanda" };
                var greg = new Student() { Id = Guid.NewGuid().ToString(), Name = "Greg" };
                var peter = new Student() { Id = Guid.NewGuid().ToString(), Name = "Peter" };
                var jessica = new Student() { Id = Guid.NewGuid().ToString(), Name = "Jessica" };
                var james = new Student() { Id = Guid.NewGuid().ToString(), Name = "James" };
                var doug = new Student() { Id = Guid.NewGuid().ToString(), Name = "Doug" };
                var cory = new Student() { Id = Guid.NewGuid().ToString(), Name = "Cory" };
                var laura = new Student() { Id = Guid.NewGuid().ToString(), Name = "Laura" };
                Students.Add(ben);
                Students.Add(andrew);
                Students.Add(amanda);
                Students.Add(greg);
                Students.Add(peter);
                Students.Add(jessica);
                Students.Add(james);
                Students.Add(doug);
                Students.Add(cory);
                Students.Add(laura);
    
                // Seed a couple sections of math and science
                var math2 = new Subject() { Id = Guid.NewGuid().ToString(), Name = "Math", ClassNumber = 2 };
                var math4 = new Subject() { Id = Guid.NewGuid().ToString(), Name = "Math", ClassNumber = 4 };
                var science5 = new Subject() { Id = Guid.NewGuid().ToString(), Name = "Science", ClassNumber = 5 };
                var science3 = new Subject() { Id = Guid.NewGuid().ToString(), Name = "Science", ClassNumber = 3 };
                Subjects.Add(math2);
                Subjects.Add(math4);
                Subjects.Add(science5);
                Subjects.Add(science3);
    
                // Seed some enrollments
                Enroll(ben.Id, math2.Id);
                Enroll(andrew.Id, math2.Id);
                Enroll(andrew.Id, science5.Id);
                Enroll(amanda.Id, math2.Id);
                Enroll(peter.Id, math2.Id);
                Enroll(jessica.Id, math4.Id);
                Enroll(james.Id, math2.Id);
                Enroll(doug.Id, math4.Id);
                Enroll(doug.Id, science5.Id);
            }
    
            public Student AddStudent(string name)
            {
                var student = new Student() { Id = Guid.NewGuid().ToString(), Name = name };
                Students.Add(student);
    
                return student;
            }
    
            public Subject AddSubject(string name, int classNumber)
            {
                var subject = new Subject() { Id = Guid.NewGuid().ToString(), Name = name, ClassNumber = classNumber };
                Subjects.Add(subject);
    
                return subject;
            }
    
            public bool DeleteStudent(string id)
            {
                try
                {
                    var student = Students.Where(s => s.Id == id).FirstOrDefault();
    
                    if (student == null) return false;
    
                    Students.Remove(student);
    
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
    
            public bool DeleteSubject(string id)
            {
                try
                {
                    var subject = Subjects.Where(s => s.Id == id).FirstOrDefault();
    
                    if (subject == null) return false;
    
                    Subjects.Remove(subject);
    
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
    
            public bool Disenroll(string studentId, string subjectId)
            {
                var student = Students.Where(s => s.Id == studentId).First();
                var subject = Subjects.Where(s => s.Id == subjectId).First();
    
                try
                {
                    student.SubjectsEnrolledIn.Remove(subjectId);
                    subject.StudentsInSubject.Remove(studentId);
                }
                catch (Exception)
                {
                    return false;
                }
    
                return true;
            }
    
            public Student EditStudent(string id, string name)
            {
                var student = Students.Where(s => s.Id == id).FirstOrDefault();
    
                if (student == null) return null;
    
                student.Name = name;
    
                return student;
            }
    
            public Subject EditSubject(string id, string name, int classNumber)
            {
                var subject = Subjects.Where(s => s.Id == id).FirstOrDefault();
    
                if (subject == null) return null;
    
                subject.Name = name;
                subject.ClassNumber = classNumber;
    
                return subject;
            }
    
            public bool Enroll(string studentId, string subjectId)
            {
                var student = Students.Where(s => s.Id == studentId).First();
                var subject = Subjects.Where(s => s.Id == subjectId).First();
    
                try
                {
                    student.SubjectsEnrolledIn.Add(subjectId);
                    subject.StudentsInSubject.Add(studentId);
                }
                catch (Exception)
                {
                    return false;
                }
    
                return true;
            }
    
            public Student GetStudent(string id)
            {
                return Students.Where(s => s.Id == id).FirstOrDefault();
            }
    
            public Subject GetSubject(string id)
            {
                return Subjects.Where(s => s.Id == id).FirstOrDefault();
            }
    
            public IEnumerable<IGrouping<string, Tuple<string, int, string>>> GetSubjectAllStudents(string id)
            {
                var tupleList = new List<Tuple<string, int, string>>();
    
                var subjectName = Subjects.Where(s => s.Id == id).FirstOrDefault()?.Name;
                var subjectList = Subjects.Where(s => s.Name == subjectName).ToList();
    
                if (subjectName == null) return null;
    
                foreach (Subject subject in subjectList)
                {
                    foreach (Student student in Students)
                    {
                        if (subject.StudentsInSubject.Contains(student.Id))
                        {
                            tupleList.Add(new Tuple<string, int, string>(student.Name, subject.ClassNumber, "yes"));
                        }
                        else
                        {
                            tupleList.Add(new Tuple<string, int, string>(student.Name, subject.ClassNumber, "no"));
                        }
                    }
                }
    
                var sortedTupleList = tupleList.GroupBy(x => x.Item1);
    
                return sortedTupleList;
            }
    
            public List<Subject> GetSubjectAlternatives(string id)
            {
                var subjectName = Subjects.Where(s => s.Id == id).FirstOrDefault()?.Name;
    
                if (subjectName == null) return null;
    
                return Subjects.Where(s => s.Name == subjectName).ToList();
            }
    
            public List<Student> ListStudents()
            {
                return Students;
            }
    
            public List<Subject> ListSubjects()
            {
                return Subjects;
            }
        }
    }
    

    Program.cs

    using System;
    using System.Collections.Generic;
    
    namespace stackoverflow61918396
    {
        class Program
        {
            static bool Again { get; set; }
            static Manager Manager { get; set; }
    
            static void Main()
            {            
                Again = true;
                Manager = new Manager();
    
                do
                {
                    Console.WriteLine("Enter a command (type 'help' for options):");
                    var selection = Console.ReadLine();
                    Console.WriteLine("\n");
    
                    CommandHandler(selection);
                } while (Again);
            }
    
            static void CommandHandler(string command)
            {
                switch (command)
                {
                    case var s when s.Trim().ToLower() == "help":
                        Console.WriteLine("Commands:");
                        Console.WriteLine("'quit' - exits the program");
                        Console.WriteLine("'students' - lists all students");
                        Console.WriteLine("'subjects' - lists all subjects");                    
                        Console.WriteLine("'student [id]' - shows this student's record");
                        Console.WriteLine("'subject [id]' - shows this subject's record");
                        Console.WriteLine("'all students by subject [id]' - lists all students in this subject or not");
                        Console.WriteLine("'alternatives for subject [id]' - lists all class numbers of a subject");
                        Console.WriteLine("'new student [name]' - adds a new student");
                        Console.WriteLine("'new subject [name] [class number]' - adds a new subject");
                        Console.WriteLine("'edit student [id] [name]' - edits an existing student");
                        Console.WriteLine("'edit subject [id] [name] [class number]' - edits an existing subject");
                        Console.WriteLine("'delete student [id]' - deletes an existing student");
                        Console.WriteLine("'delete subject [id]' - deletes an existing subject");
                        Console.WriteLine("'enroll [student id] [subject id]' - enrolls a student into a subject");
                        Console.WriteLine("'disenroll [student id] [subject id]' - disenrolls a student from a subject");
                        Console.WriteLine("\n");
                        break;
                    case var s when s.Trim().ToLower() == "quit":
                        Again = false;
                        break;
                    case var s when s.Trim().ToLower() == "students":
                        try
                        {
                            List<Student> studentList = Manager.ListStudents();
    
                            if (studentList == null) throw new Exception();
    
                            Console.WriteLine("Students:");
                            foreach (Student student in studentList)
                            {
                                Console.WriteLine("Id: " + student.Id + ", Name: " + student.Name);
                            }
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower() == "subjects":
                        try
                        {
                            List<Subject> subjectList = Manager.ListSubjects();
    
                            if (subjectList == null) throw new Exception();
    
                            Console.WriteLine("Subjects:");
                            foreach (Subject subject in subjectList)
                            {
                                Console.WriteLine(
                                    "Id: " + subject.Id +
                                    ", Class Number: " + subject.ClassNumber +
                                    ", Name: " + subject.Name
                                );
                            }
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("student"):
                        try
                        {
                            var studentId = s.Split(' ')[1];
                            var student = Manager.GetStudent(studentId);
    
                            if (student == null) throw new Exception();
    
                            Console.WriteLine("Id: " + student.Id + ", Name: " + student.Name);
    
                            Console.WriteLine("Subjects Enrolled In:");
                            foreach (string subjectId in student.SubjectsEnrolledIn)
                            {
                                var subject = Manager.GetSubject(subjectId);
                                Console.WriteLine(
                                    "Id: " + subject.Id + 
                                    ", Class Number: " + subject.ClassNumber + 
                                    ", Name: " + subject.Name
                                );
                            }
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("subject"):
                        try
                        {
                            var subjectId = s.Split(' ')[1];
                            var subject = Manager.GetSubject(subjectId);
    
                            if (subject == null) throw new Exception();
    
                            Console.WriteLine("Id: " + subject.Id + ", Name: " + subject.Name);
    
                            Console.WriteLine("Students In Subject:");
                            foreach (string studentId in subject.StudentsInSubject)
                            {
                                var student = Manager.GetStudent(studentId);
                                Console.WriteLine(
                                    "Id: " + student.Id +
                                    ", Name: " + student.Name
                                );
                            }
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("all"):
                        try
                        {
                            var subjectId = s.Split(' ')[4];
                            var subjectName = Manager.GetSubject(subjectId)?.Name;
                            var subjectWithAll = Manager.GetSubjectAllStudents(subjectId);
    
                            if (subjectWithAll == null) throw new Exception();
    
                            Console.WriteLine("All students with respect to " + (subjectName ?? subjectId) + ":");
                            foreach (var group in subjectWithAll)
                            {
                                foreach (var item in group)
                                {
                                    Console.WriteLine(
                                        "\tName: " + item.Item1 +
                                        ", \t\tClass Number: " + item.Item2 +
                                        ", \t\tEnrolled: " + item.Item3
                                    );
                                }
                            }
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("alternatives"):
                        try
                        {
                            var subjectId = s.Split(' ')[3];
                            List<Subject> subjectAlternatives = Manager.GetSubjectAlternatives(subjectId);
    
                            if (subjectAlternatives == null) throw new Exception();
    
                            Console.WriteLine("Alternatives for " + subjectAlternatives[0].Name + ":");
                            foreach (Subject subject in subjectAlternatives)
                            {
                                Console.WriteLine("Id: " + subject.Id + ", Class Number: " + subject.ClassNumber);
                            }
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("new student"):
                        try
                        {
                            var name = s.Split(' ')[2];
                            var student = Manager.AddStudent(name);
    
                            if (student == null) throw new Exception();
    
                            Console.WriteLine("Student " + student.Id + " created");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("new subject"):
                        try
                        {
                            var name = s.Split(' ')[2];
                            var classNumber = s.Split(' ')[3];
                            var subject = Manager.AddSubject(name, int.Parse(classNumber));
    
                            if (subject == null) throw new Exception();
    
                            Console.WriteLine("Subject " + subject.Id + " created");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("edit student"):
                        try
                        {
                            var studentId = s.Split(' ')[2];
                            var studentName = s.Split(' ')[3];
                            var student = Manager.EditStudent(studentId, studentName);
    
                            if (student == null) throw new Exception();
    
                            Console.WriteLine("Student " + student.Id + " was edited");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("edit subject"):
                        try
                        {
                            var subjectId = s.Split(' ')[2];
                            var subjectName = s.Split(' ')[3];
                            var subjectClassNumber = s.Split(' ')[4];
                            var subject = Manager.EditSubject(subjectId, subjectName, int.Parse(subjectClassNumber));
    
                            if (subject == null) throw new Exception();
    
                            Console.WriteLine("Subect " + subject.Id + " was edited");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("delete student"):
                        try
                        {
                            var studentId = s.Split(' ')[2];
                            var deleted = Manager.DeleteStudent(studentId);
    
                            Console.WriteLine("Student was " + (deleted ? "" : "not") + " deleted");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("delete subject"):
                        try
                        {
                            var subjectId = s.Split(' ')[2];
                            var deleted = Manager.DeleteSubject(subjectId);
    
                            Console.WriteLine("Subject was " + (deleted ? "" : "not") + " deleted");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("enroll"):
                        try
                        {
                            var studentId = s.Split(' ')[1];
                            var subjectId = s.Split(' ')[2];
                            var enrolled = Manager.Enroll(studentId, subjectId);
    
                            Console.WriteLine("Student was " + (enrolled ? "" : "not") + " enrolled");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    case var s when s.Trim().ToLower().StartsWith("disenroll"):
                        try
                        {
                            var studentId = s.Split(' ')[1];
                            var subjectId = s.Split(' ')[2];
                            var disenrolled = Manager.Disenroll(studentId, subjectId);
    
                            Console.WriteLine("Student was " + (disenrolled ? "" : "not") + " disenrolled");
                            Console.WriteLine("\n");
                        }
                        catch (Exception)
                        {
                            Console.WriteLine("Unrecognized command. Please try again.");
                            Console.WriteLine("\n");
                        }
                        break;
                    default:
                        Console.WriteLine("Unrecognized command. Please try again.");
                        Console.WriteLine("\n");
                        break;
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多