您将如何使用 LINQ 查询语法编写这个完全相同的查询?
var q2 = list.GroupBy(x => x.GroupId)
.Select(g => g
.OrderByDescending(x => x.Date)
.FirstOrDefault());
我虽然这应该工作,但它没有:
var q1 = from x in list
group x by x.GroupId into g
from y in g
orderby y.Date descending
select g.FirstOrDefault();
如果你想玩它,这里有一个测试程序:
public class MyClass
{
public int Id { get; set; }
public string GroupId { get; set; }
public DateTime Date { get; set; }
public override bool Equals(object obj)
{
var item = obj as MyClass;
return item == null ? false : item.Id == this.Id;
}
}
static void Main(string[] args)
{
var list = new List<MyClass>
{
new MyClass { GroupId = "100", Date=DateTime.Parse("01/01/2000"), Id = 1},
new MyClass { GroupId = "100", Date=DateTime.Parse("02/01/2000"), Id = 2},
new MyClass { GroupId = "200", Date=DateTime.Parse("01/01/2000"), Id = 3},
new MyClass { GroupId = "200", Date=DateTime.Parse("02/01/2000"), Id = 4},
new MyClass { GroupId = "300", Date=DateTime.Parse("01/01/2000"), Id = 5},
new MyClass { GroupId = "300", Date=DateTime.Parse("02/01/2000"), Id = 6},
};
var q1 = from x in list
group x by x.GroupId into g
from y in g
orderby y.Date descending
select g.FirstOrDefault();
var q2 = list.GroupBy(x => x.GroupId)
.Select(g => g
.OrderByDescending(x => x.Date)
.FirstOrDefault());
Debug.Assert(q1.SequenceEqual(q2));
}