我是LINQ的新手,我在转换方面遇到了一些问题。我必须编写一种方法,找到所有在姓氏前按字母顺序排列名字的学生。这是我的代码:
static Student[] FindAllFirstNameBeforeSecond(Student[] students)
{
Student[] newStudents =
from student in students
where student.FirstName.CompareTo(student.LastName) < 0
select student;
return newStudents;
}
我收到了这个错误:
Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<ConsoleApplication2.Student>'
to 'ConsoleApplication2.Student[]'.
An explicit conversion exists (are you missing a cast?)
我可以获得一些关于我做错的提示吗?
答案 0 :(得分:4)
Linq查询返回IEnumerable<Student>
类型的结果。你应该将它转换为数组:
static Student[] FindAllFirstNameBeforeSecond(Student[] students)
{
IEnumerable<Student> newStudents =
from student in students
where student.FirstName.CompareTo(s.LastName) < 0
select student;
return newStudents.ToArray();
}
在这种情况下,BTW lambda语法更紧凑:
static Student[] FindAllFirstNameBeforeSecond(Student[] students)
{
return students.Where(s => s.FirstName.CompareTo(student.LastName) < 0)
.ToArray();
}
此外,您可以使用s.FirstName < s.LastName
和Array.FindAll
(如果您希望将结果作为数组):
static Student[] FindAllFirstNameBeforeSecond(Student[] students)
{
return Array.FindAll(students, s => s.FirstName < s.LastName);
}