私は、タイプ、日付、および値を含む一連のデータを持っています。どのようにしてグループ内の要素をlinqクエリで並べ替え、最初の?
タイプごとにグループ化したいと思います。各グループの値のセットごとに、最新の日付のグループを選択したいと思います。
ここでは、動作し、正しい結果を与えるいくつかのコードですが、私は繰り返しではなく、1つのlinqクエリですべて行いたいと思います。純粋にlinqクエリでこれと同じ結果をどのように達成することができますか?
using System;
using System.Linq;
using System.Collections.Generic;
public class Program {
public static void Main() {
var mydata = new List<Item> {
new Item { Type = "A", Date = DateTime.Parse("2016/08/11"), Value = 1 },
new Item { Type = "A", Date = DateTime.Parse("2016/08/12"), Value = 2 },
new Item { Type = "B", Date = DateTime.Parse("2016/08/20"), Value = 3 },
new Item { Type = "A", Date = DateTime.Parse("2016/08/09"), Value = 4 },
new Item { Type = "A", Date = DateTime.Parse("2016/08/08"), Value = 5 },
new Item { Type = "C", Date = DateTime.Parse("2016/08/17"), Value = 6 },
new Item { Type = "B", Date = DateTime.Parse("2016/08/30"), Value = 7 },
new Item { Type = "B", Date = DateTime.Parse("2016/08/18"), Value = 8 },
};
var data = mydata.GroupBy(_ => _.Type);
foreach (var thing in data) {
#region
// How can I remove this section and make it part of the group by query above... ?
var subset = thing.OrderByDescending(_ => _.Date);
var top = subset.First();
#endregion
Console.WriteLine($"{thing.Key} {top.Date.ToString("yyyy-MM-dd")} {top.Value}");
}
}
public class Item {
public string Type {get;set;}
public DateTime Date {get;set;}
public int Value {get;set;}
}
}
// Output:
// A 2016-08-12 2
// B 2016-08-30 7
// C 2016-08-17 6
。 – sstan