我有一个任务是创建一个类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; }
}
}
然后我编码了这个:
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;
}
}
不幸的是,关键字where有一个错误,我无法完全理解:
无法隐式转换类型 'System.Collections.Generic.IEnumerable'到 'System.Collections.Generic.List'。显式转换 存在(你错过了演员?)。
你能帮我理解究竟出了什么问题吗?
答案 0 :(得分:9)
使用ToList()
方法枚举结果并将其放入列表中:
var query = from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0
select student;
List<Student> sortedStudents = query.ToList();
或者在一个声明中:
List<Student> sortedStudents = (from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0
select student).ToList();
答案 1 :(得分:3)
您的错误意味着您的流利Linq将返回IEnumerable<Student>
,而不是您期望的List<Student>
。您需要额外.ToList()
来电,或者您可以使用IEnumerable<Student>
。
答案 2 :(得分:2)
您只需将linq表达式转换为列表:
List<Student> sortedStudents = (from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0 select student).ToList();
答案 3 :(得分:2)
此查询,
from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0
select student
返回IEnumerable<Student>
。
如果您想要List<Student>
,则应在结果ToList()
上致电IEnumerable<Student>
:
List<Student> sortedStudents =
(from student in students
where student.FirstName.CompareTo(student.FamilyName) < 0
select student)
.ToList();
请注意,作为一般规则,LINQ查询在枚举结果时进行评估,而不是之前(这称为“延迟执行”或“延迟加载”)。但是,调用ToList()
会立即执行查询,枚举结果并填充列表。
答案 4 :(得分:1)
您应该在声明的末尾添加.ToList()
。
这会将您的Enumerable转换为List
答案 5 :(得分:1)
将.ToList()添加到您的查询中:
List<Student> sortedStudents = (from student in students where student.FirstName.CompareTo(student.FamilyName) < 0 select student).Tolist();