如何为学生和多个课程成绩创建字典?

时间:2017-11-30 06:28:31

标签: c# list dictionary generics

我正在学习C#字典,我很困惑如何做到这一点

我有一个学生名字词典。我想为此分配另一本字典。

我的输入与此相似

Student1:  数学,9  科学,5  英语,2

STUDENT2:  数学,9  科学,10  英,7

我尝试创建一个名为Info的类,这是我的代码

public class Info
    {
        public string course { get; set; }
        public int grade { get; set; }

        public Info(string c, int g)
        {
            course = c;
            grade = g;
        }

    }


    class Test
    {
        public static void Main(string[] args)
        {

            Dictionary<string, Info> information = new Dictionary<string, Info>();
            Info i1 = new Info("math", 9);
            information.Add("Student1", i1);
            Info i2 = new Info("science", 11);
            information.Add("Student1", i2);
            Info i3 = new Info("math", 13);
            information.Add("student2", i3);

            foreach (KeyValuePair<string, Info> eee in information)
            {
                Console.WriteLine("{0}\t{1}\t{2}", eee.Key, eee.Value.type, eee.Value.count);
            }

        }
    }

这是另一次尝试:

我尝试制作课程信息,主要是我创建字典并给出值,但问题是我可以说3门课程和10个学生,有时我只需要检索所有的数学成绩学生们。

如何改进代码以区分课程?或者如何将课程名称作为另一个关键?

// Server
Meteor.publish('userData', function () {
  if (this.userId) {
    return Meteor.users.find({ _id: this.userId }, {
      fields: { groups: 1 }
    });
  } else {
    this.ready();
  }
});

我需要两个方法来设置用户输入的值,另一个用于在用户需要时检索某个课程值

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

我从您的陈述中了解到,您需要两种方法:一种用于设置用户值,另一种用于获取用户的课程价值,我为了满足您的要求,我稍微修改了您的代码,您可以这样做:

public class Info
    {
        public string course { get; set; }
        public int grade { get; set; }

        public Info(string c, int g)
        {
            course = c;
            grade = g;
        }

    }

    public class Student
    {
        public Dictionary<string,Dictionary<string,int>> student { get; set; }
        public Student()
        {
            student = new Dictionary<string, Dictionary<string, int>>();
        }

        /// <summary>
        /// 
        /// </summary>
        public void SetValue(string studentName, Info info)
        {

            if (!student.ContainsKey(studentName))
            {
                Dictionary<string, int> stud_info = new Dictionary<string, int>();
                stud_info.Add(info.course, info.grade);
                student.Add(studentName, stud_info);
            }
            else
            {
                student[studentName].Add(info.course, info.grade);
            }
        }


        public Dictionary<string,int> GetValue(string studentName, string course)
        {
            Dictionary<string, int> info = new Dictionary<string, int>();
            if (student.ContainsKey(studentName))
            {
                if (student[studentName].ContainsKey(course))
                {
                    int grade = 0;
                    if(student[studentName].TryGetValue(course, out grade))
                    {
                        info.Add(course, grade);
                        return info;
                    }
                }
            }
            return info;
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            Info i1 = new Info("math", 9);
            student.SetValue("Student1", i1);
            Info i2 = new Info("science", 11);
            student.SetValue("Student1",i2);
            Info i3 = new Info("math", 13);
            student.SetValue("Student2", i3);

            Dictionary<string, int> value = student.GetValue("Student2", "math");
            //Grade of math for student2
            Console.WriteLine("Grade: {0}", value["math"]);
        }


    }

答案 1 :(得分:1)

将问题分解为单独的问题。

仅使用dup2(fd2, STDOUT_FILENO)Student类来存储数据。重要的是,每个学生都会收集他的课程。

Info

数据访问由不同的类public class Student { public Student(string name) { Name = name; Infos = new List<Info>(); } public string Name {get; set;} public ICollection<Info> Infos {get; set;} } public class Info { public Info(string course, int grade) { Course = course; Grade = grade; } public string Course { get; set; } public int Grade { get; set; } } 处理。 中心字典的类型为StudentRepository,学生名称为密钥,并隐藏在存储库中。

IDictionary<string, Student>

用法示例:

using System.Linq;

public class StudentRepository {
    public StudentRepository() {
       _studentsByName = new Dictionary<string, Student>();
    }

    // keep data store private so we can change the implementation
    private IDictionary<string, Student> _studentsByName {get; set;}

    public void Add(Student student) {
        if (_studentsByName.ContainsKey(student.Name)) {
           throw new ArgumentException($"Student '{student.Name}' already stored.");
        }
        _studentsByName.Add(student.Name, student);
    }

    public Student Get(string studentName) {
        if (_studentsByName.ContainsKey(studentName)) {
           return _studentsByName[studentName];
        }
        throw new ArgumentException("No student '" + studentName + "' stored.");
    }

    // Find Grade for certain student and course
    public int GetGrade(string studentName, string course) {
        if (_studentsByName.ContainsKey(studentName)) {
            var student = _studentsByName[studentName];
            var courseInfo = student.Infos.FirstOrDefault(i => i.Course == course);
            if (courseInfo != null) {
                return courseInfo.Grade;
            }
            else {
                throw new ArgumentException(
                    $"Student '{studentName}' did not take the course '{course}'.");
            }
        }
        else {
            throw new ArgumentException($"No student '{studentName}' found.");
        }
    }

    // Get dictionary of all students that took a certain course. Key: student name
    public IDictionary<string, Info> GetCoursesByStudentName(string course) {

        // Use LINQ to retrieve the infos you need. 
        // Here I create a new dictionary with Student name as Key and 
        // the first matching course info found as value.
        // (Students that did not take this course are not in this dictionary):
        return _studentsByName 
            .Where(kvp => kvp.Value.Infos.Any(i => i.Course == course))
            .ToDictionary(kvp => kvp.Key, 
                          kvp => kvp.Value.Infos.First(i => i.Course == course));
    }
}

C# Fiddle for this example