在下面的代码中,filteredStudentNames
为什么只包含2个元素。
根据我的理解,它是引用类型,因此当我用另外一项更新studentList
对象时,结果也应该是filteredStudentNames
的一部分。
对于studentNames
对象,我也正在获取更新的记录。
那么为什么不使用filteredStudentnames
?
static void Main(string[] args)
{
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , age = 21 }
};
var filteredStudentNames = from s in studentList
where s.age > 20
select s;
var studentNames = from s in studentList
select s;
IList<Student> stud = studentList;
studentList.Add(new Student { StudentID = 27, StudentName = "Test" });
答案 0 :(得分:1)
filteredStudentNames
查询 age > 20
。添加新学生时,您尚未启动age属性,这意味着默认情况下为0。
因此它没有反映在filteredStudentNames
尝试启动age
属性,然后查询Count
studentList.Add(new Student { StudentID = 6, StudentName = "Test", age = 21 });
计数:
Console.WriteLine("filteredStudentNames: " + filteredStudentNames.Count()); //Output: 3
Console.WriteLine("studentNames: " + studentNames.Count()); //Output: 6
答案 1 :(得分:-1)
我很确定这对您有用。
static void Main(string[] args)
{
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , age = 21 }
};
var filteredStudentNames = from s in studentList where s.age > 20
select s;
var studentNames = from s in studentList
select s;
IList<Student> stud = studentList;
studentList.Add(new Student { StudentID = 27, StudentName = "Test", age = 25 });
var filteredStudentNames = from s in studentList where s.age > 20
select s;
}
添加新条目后必须执行链接,并且必须为新条目添加年龄。 谢谢。