简单的LINQ / Lambda查询不编译

时间:2017-02-02 07:38:12

标签: c# asp.net

我是linq的新手,我很难抓住它。

我的代码是一个linq,应该过滤所有1984年以前出生的同学Allstudents学生。我第一次来这里的片段很抱歉。

private void Linq2()
    {
        Header("Linq2");

                    var Student = from B in TestData.AllStudents
                      where TestData.AllStudents.Where(x => x.Birthday.Year > 1984)
                      select B;

    }



 public static List<Student> AllStudents
        {
            get
            {
                return new List<Student>
                {
                    new Student {Id=1, FirstName="Lisa", Birthday=new DateTime(1980, 1, 1), FavoriteSubject="Geography", NumberOfOwnedBooks=10},
                    new Student {Id=2, FirstName="Ali", Birthday=new DateTime(1985, 2, 2), FavoriteSubject="Geography", NumberOfOwnedBooks=10},
                    new Student {Id=4, FirstName="George", Birthday=new DateTime(1960, 3, 3), FavoriteSubject="Mathematics", NumberOfOwnedBooks=20},
                    new Student {Id=5, FirstName="Susan", Birthday = new DateTime(1960, 3, 3), FavoriteSubject = "Mathematics", NumberOfOwnedBooks = 30 },
                    new Student {Id=3, FirstName="Britney", Birthday=new DateTime(1980, 1, 1), FavoriteSubject="Mathematics", NumberOfOwnedBooks=40},
                };
            }
        }

错误CS0029无法隐式转换类型&#39; System.Collections.Generic.IEnumerable&#39;到了布尔&#39;

错误CS1662无法将查询表达式转换为预期的委托类型,因为块中的某些返回类型不能隐式转换为委托返回类型
编辑代码片段

3 个答案:

答案 0 :(得分:4)

您正在查询表达式语法中混合使用lambda查询语法,实际上是您在第一行(from B in TestData.AllStudents)中创建的别名,因为B需要在where子句中使用where B.Birthday.Year > 1984。 1}}正如你在select部分写的那样:

var Students = from B in TestData.AllStudents
                      where B.Birthday.Year > 1984
                      select B;

如果你想使用lambda表达式版本,那么它应该是:

var Students = TestData.AllStudents.Where(x => x.Birthday.Year > 1984);

答案 1 :(得分:2)

人们只能猜测,因为你没有发布实际的编译错误,但TestData.AllStudents.Where(x => x.Birthday.Year > 1984)肯定是错误的。只需写下:

var students = from B in TestData.AllStudents
               where B.Birthday.Year > 1984
               select B;

对所有变量使用描述性名称是个好主意:

var students = from student in TestData.AllStudents
               where student.Birthday.Year > 1984
               select student;

如果您不想使用查询格式,可以使用:

var students=TestData.AllStudents
                     .Where(student=>student.Birthday.Year > 1984);

结果在所有情况下都相同:您可以迭代的IEnumerable<Student>,或转换为ToList()的列表或ToArray()等数组

答案 2 :(得分:0)

您可以使用

var stds = dbContext.AllStudents.Where(m=>m.Birthday.Year>1984);
return stds.ToList();