【发布时间】:2016-08-11 14:16:35
【问题描述】:
我有一组包含类型、日期和值的数据。
我想按类型分组,对于每个组中的每组值,我想选择日期最新的那个。
这里有一些代码可以工作并给出正确的结果,但我想在一个 linq 查询中而不是在迭代中完成这一切。有什么想法可以通过纯粹的 linq 查询实现与此相同的结果...?
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}");
}
其中Item定义为:
public class Item {
public string Type {get;set;}
public DateTime Date {get;set;}
public int Value {get;set;}
}
预期输出:
A 2016-08-12 2
B 2016-08-30 7
C 2016-08-17 6
【问题讨论】:
-
使用下划线作为您实际使用的参数的参数名称是非常不寻常的。