假设我有一个包含以下字段的 Person 对象的数据库:
class Person
{
public DateTime BirthDate { get; set; }
public string CountryOfBirth { get; set; }
}
我想使用一个查询(LINQ 或其他一些 C# 代码(来搜索仅在(例如(美国出生Person
的birthDate
,并返回具有最大birthDate
的Person
。如果这一天出生了不止一个Person
,它应该返回所有。
有什么方法可以做到这一点?
嗯,听起来你想:
- 按国家/地区筛选
- 按出生日期分组
- 按降序对组进行排序
- 取第一组
所以(假设属性名称已固定为遵循约定(:
var query = db.People
.Where(p => p.CountryOfBirth == "USA")
.GroupBy(p => p.BirthDate)
.OrderByDescending(p => p.Key)
.FirstOrDefault();
如果没有团体,这将返回null
,因为没有在美国出生的人。要返回一个空序列,您可以平展第一个结果(如果有(:
var query = db.People
.Where(p => p.CountryOfBirth == "USA")
.GroupBy(p => p.BirthDate)
.OrderByDescending(p => p.Key)
.Take(1)
.SelectMany(p => p);
如果
有帮助,我知道如何在 2 个查询中做到这一点。看看这个:https://dotnetfiddle.net/c3BNWp
法典:
public class Program
{
public static void Main()
{
var list = new List<Person>(){
new Person(){
Name = "1",
countryOfBirth = "USA",
birthDate = new DateTime(2000,1,1)
},
new Person(){
Name = "2",
countryOfBirth = "USA",
birthDate = new DateTime(1999,1,1)
},
new Person(){
Name = "3",
countryOfBirth = "USA",
birthDate = new DateTime(2000,1,1)
},
new Person(){
Name = "4",
countryOfBirth = "Other",
birthDate = new DateTime(2000,1,1)
},
new Person(){
Name = "5",
countryOfBirth = "SomeOther",
birthDate = new DateTime(2000,1,1)
}
};
var max = list.Where(p=> p.countryOfBirth == "USA").Max(a=> a.birthDate);
Console.WriteLine(max);
var maxList = list.Where(p=> p.countryOfBirth == "USA" && p.birthDate == max).ToList();
foreach(var p in maxList){
Console.WriteLine(p.Name);
}
}
}
class Person
{
public string Name {get; set;}
public DateTime birthDate { get; set; }
public string countryOfBirth { get; set; }
}