我有一个任务是创建一个类Student并创建一个方法,只有当他们的名字在使用LINQ查询运算符的字母顺序排在他们的姓氏之前时才从数组中选择Students.我写过这Student堂课:
public class Student
{
private string firstName;
private string familyName;
private int age;
public Student(string firstName, string familyName, int age)
: this()
{
this.firstName = firstName;
this.familyName = familyName;
this.age = age;
}
public Student()
{
firstName = "Dancho";
familyName = "Mastikata";
age = 24;
this.firstName = firstName;
this.familyName = familyName;
this.age = age;
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string FamilyName
{
get { return familyName; }
set { familyName = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
然后我编码了这个:
public class StudentsManipulations
{
static void Main()
{
Student[] students = new Student[6]{new Student("Georgi", "Milanov", 21 ),
new Student("Ilko", "Pirgov", 30 ),
new Student("Neboisha", "Yelenkovich", 34),
new Student("Dimitar", "Berbatov", 32 ),
new Student( ),
new Student("Nikolai", "Bodurov", 24 )};
}
public static List<Student> StudentSortByFirstName(Student[] students)
{
List<Student> sortedStudents = from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0
select student;
return sortedStudents;
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,关键字在哪里出错,我无法完全理解:
无法将类型'System.Collections.Generic.IEnumerable'隐式转换为'System.Collections.Generic.List'.存在显式转换(您是否错过了演员?).
你能帮我理解究竟是什么问题吗?
使用ToList()方法枚举结果并将它们放入列表中:
var query = from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0
select student;
List<Student> sortedStudents = query.ToList();
Run Code Online (Sandbox Code Playgroud)
或者在一个声明中:
List<Student> sortedStudents = (from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0
select student).ToList();
Run Code Online (Sandbox Code Playgroud)