新手在这里,我的代码有问题。在此代码返回一个字符串数组(学生名称)之前,我需要添加学生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;
}
答案 0 :(得分:1)
您可以在select子句中使用匿名类,即
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类,您可能希望在初始化程序中更改prop。
students = group.Students
.Select(r => new Student {
StudentName= r.StudentName,
StudentID= r.StudentID
})
.ToArray();