我有一组包含类型,日期和值的数据.
我想按类型分组,并且对于每组中的每组值,我想选择具有最新日期的那组.
这里有一些代码可以工作并给出正确的结果,但我想在一个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
Run Code Online (Sandbox Code Playgroud)
使用select来获取FirstOrDefault(或First-有序下降,因为分组,你不会得到一个空的):
var data = mydata.GroupBy(item => item.Type)
.Select(group => group.OrderByDescending(x => x.Date)
.FirstOrDefault())
.ToList();
Run Code Online (Sandbox Code Playgroud)
或者SelectMany与...一起Take(1)
var data = mydata.GroupBy(item => item.Type)
.SelectMany(group => group.OrderByDescending(x => x.Date)
.Take(1))
.ToList();
Run Code Online (Sandbox Code Playgroud)