0

新手,我的代码有问题。在此代码返回一个字符串数组(学生姓名)之前,但我需要添加学生 ID,而不需要我重新编码整个方法。有人可以帮我怎么做吗?基本上我需要包括基于学生姓名的学生证。

TIA。

public Student[] GetAllStudents(string subject)
    { 
        Student[] students = cache.GetAllStudents(subject);

        if (students == null)
        {
            Subjects group = RetrieveSubjects(subject);

            if (group != null)
            {
                students = group.Students.Select(r => r.StudentName).ToArray();
                // I need to include also the Student ID based on the Student Name queried above.

            }
            else
            {
                students = new string[0];
            }

            cache.AddAllStudents(subject, students);
        }

        return students;
    }
4

1 回答 1

1

您可以在选择子句中使用匿名类,即

students = group.Students
                  .Select(r => new { name= r.StudentName, id= r.StudentID } )
                  .ToArray();

或者只是选择学生对象,因为它应该有你需要的一切

students = group.Students.ToArray();

// doing .Select(r=>r) is redundant and can be omited

似乎您需要从您的 studentinfo 类创建 Student 类,您可能希望更改初始化程序中的道具。

students = group.Students
                  .Select(r => new Student { 
                         StudentName= r.StudentName, 
                         StudentID= r.StudentID 
                   })
                  .ToArray();
于 2013-03-11T07:13:40.540 回答