简体   繁体   中英

Read matching records from hashtable into class object

In my asp.net app I have a class that contains InstructorID and InstructorName .
In the old code, I have a System.Collections.Hashtable that contains InstructorName ( value ) and StudentID ( key ).

What I would like to do is add the studentID to my class object (where InstructorName = InstructorName ), and given that one instructor can have many students associated, however, one student can only have one instructor..

My class objects is:

public class ClassInstructor
{
    public int InstructorID { get; set; }
    public string InstructorName { get; set; }
    public List<string> studentID { get; set; }
}

How would I accomplish that?
Or is there a better way of doing this?

If your hash table is a Dictionary where the key is the StudentID and the value is the InstructorName, you could do the following:

Dictionary<string, string> studentTeachers = new Dictionary<string, string>();
studentTeachers.Add("Student #1", "Instructor #1");
studentTeachers.Add("Student #2", "Instructor #1");
studentTeachers.Add("Student #3", "Instructor #1");
studentTeachers.Add("Student #4", "Instructor #1");
studentTeachers.Add("Student #5", "Instructor #2");
studentTeachers.Add("Student #6", "Instructor #2");
studentTeachers.Add("Student #7", "Instructor #2");
studentTeachers.Add("Student #8", "Instructor #2");

var instructors = new List<ClassInstructor>();

instructors.Add(new ClassInstructor() { InstructorID = 1, InstructorName = "Instructor #1" });
instructors.Add(new ClassInstructor() { InstructorID = 2, InstructorName = "Instructor #2" });

foreach (var instructor in instructors)
    instructor.Students = studentTeachers.Where(x => x.Value == instructor.InstructorName).Select(x => x.Key).ToList();

Since you didn't post a lot of code you may need to adapt this to work with your specific objects. This is also assuming that the collection of instructors has already been populated and that you are replacing any references to students that may already exist. It's also assuming that your instructor name strings will match exactly, if not you may need to perform a more lenient string comparison.

Basically in this code you're using LINQ to populate each Students collection with a list of strings that you projected from the hash table based on matching keys.

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.

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