Linq将查询表示为Lambda查询

本文关键字:查询 Lambda 表示 查询表 Linq | 更新日期: 2023-09-27 17:57:50

我创建了一个查询,只显示出生日期小于1990年的学生。我试图将这个查询表示为Lambda查询,但不知道如何进行。这是我迄今为止的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public DateTime DateOfBirth { get; set; }
}
class LINQ2
{
    static void Main()
    {
        IEnumerable<Student> students = new List<Student>()
        {
            new Student {FirstName = "Jim", LastName = "Smith", DateOfBirth = new DateTime(1990, 5, 21), ID = 1},
            new Student {FirstName = "Diane", LastName = "Sawyer", DateOfBirth = new DateTime(1992, 11, 1), ID = 2},
            new Student {FirstName = "Steve", LastName = "Thomas", DateOfBirth = new DateTime(1994, 4, 4), ID = 3},
            new Student {FirstName = "Pablo", LastName = "Dicaz", DateOfBirth = new DateTime(1973, 3, 30), ID = 4},
            new Student {FirstName = "Hannu", LastName = "Korppi", DateOfBirth = new DateTime(1988, 6, 16), ID = 5},
            new Student {FirstName = "Marie", LastName = "St. Claude", DateOfBirth = new DateTime(1982, 1, 19), ID = 6}
        };
        IEnumerable<Student> query = from s in students
                                     where s.DateOfBirth.Year < 1990
                                     orderby s.FirstName
                                     select s;

        foreach (Student stud in query)
        {
            Console.WriteLine(stud.FirstName);
            Console.ReadLine();  
        }
    }
}
}

Linq将查询表示为Lambda查询

如果你指的是Lambda查询的扩展方法语法,那么你可以这样做:

var query = students
            .Where(s => s.DateOfBirth.Year < 1990)
            .OrderBy(s => s.FirstName);