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));
}