gpt4 book ai didi

c# - Linq 将查询表达为 Lambda 查询

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:39 26 4
gpt4 key购买 nike

我创建了一个查询,它只显示出生日期小于 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();
}
}
}
}

最佳答案

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

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

关于c# - Linq 将查询表达为 Lambda 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com