在Linq中在哪里创建对象的新实例

时间:2018-10-31 10:52:02

标签: c# linq

在下面的代码中,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" });

2 个答案:

答案 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;

}

添加新条目后必须执行链接,并且必须为新条目添加年龄。 谢谢。