【问题标题】:Read matching records from hashtable into class object将匹配记录从哈希表读入类对象
【发布时间】:2013-10-07 21:38:41
【问题描述】:

在我的 asp.net 应用程序中,我有一个包含 InstructorIDInstructorName 的类。
在旧代码中,我有一个 System.Collections.Hashtable,其中包含 InstructorName (value) 和 StudentID (key)。

我想做的是将studentID 添加到我的班级对象(其中InstructorName = InstructorName),并且鉴于一名教师可以关联许多学生,但是,一名学生只能有一名教师..

我的班级对象是:

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

我将如何做到这一点?
或者有更好的方法吗?

【问题讨论】:

  • 一个学生可以只有一个导师吗?
  • @TrevorElliott,这是正确的。我更新了帖子。

标签: c# asp.net generics collections hashtable


【解决方案1】:

如果您的哈希表是一个字典,其中键是 StudentID,值是 InstructorName,您可以执行以下操作:

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

由于您没有发布大量代码,您可能需要对其进行调整以适用于您的特定对象。这还假设已经填充了教师集合,并且您正在替换对可能已经存在的学生的任何引用。它还假设您的讲师姓名字符串将完全匹配,否则您可能需要执行更宽松的字符串比较。

基本上,在此代码中,您使用 LINQ 使用您根据匹配键从哈希表投影的字符串列表填充每个学生集合。

【讨论】:

  • 您的上述假设是正确的。感谢您的帮助。我会试试这个,让你知道。
  • 如果我遵循您的代码,您正在将 'students' 从 Hashtable 转换为字典,对吗?
  • 不...我正在将字典转换为可以添加到每个ClassInstructor 的字符串列表,假设您的 StudentID -> InstructorName 集合是字典。您没有指定您的哈希表由哪个类表示。
  • 哈希表是一个“System.Collections.Hashtable”。当我运行您的代码时,我在 Where .... System.Collections.Hashtable' 不包含“Where”的定义时收到错误消息
  • 您也可以这样做foreach (var instructor in instructors.ToArray()) { if (instructor.Students.Count == 0) instructors.Remove(instructor); } 在这种情况下,您必须将讲师转换为数组以枚举它们,因为在 foreach 中枚举时无法修改集合。但是,我更喜欢使用 LINQ 的上述方法,因为它更简洁。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-21
  • 2012-05-02
  • 1970-01-01
  • 2011-06-07
  • 2012-05-18
相关资源
最近更新 更多