c# - 简单的 LINQ/Lambda 查询未编译

标签 c# asp.net

我是 linq 的新手,很难掌握它。

我的代码是一个 linq,它应该从 Allstudents 类中过滤出 1984 年之前出生的所有学生。抱歉这些片段,我第一次来这里。

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 无法将类型“System.Collections.Generic.IEnumerable”隐式转换为“bool”

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

最佳答案

您在查询表达式语法中混合了 lambda 查询语法,实际上是您在第一行中创建的别名(来自 TestData.AllStudents 中的 B),因为 B需要像 where B.Birthday.Year > 1984 那样在 where 子句中使用 down,正如您在 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);

关于c# - 简单的 LINQ/Lambda 查询未编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41996581/

相关文章:

c# - ((System.Object)p == null)

c# - 在流畅的界面中实现条件

c# - 如何在 Visual 2013 上安装 Hot Towel SPA,我在网页部分看不到模板

.net - 实现通用 Web 服务 API 的最佳方式

asp.net - Web.config 中的 Sql Server Express 和连接字符串

c# - asp.net中如何根据teamviewerid启动teamviewer session

c# - 弹出 View 时是否有 iOS 覆盖?

c# - 如何使用 ?字符串关键字

javascript - 排序 Jquery 返回的 HTML 元素

asp.net - 如何使 ASP.NET MVC 站点像 ASP.NET Web 窗体站点一样可进行单元测试?