我有一个日期列表。我想从该列表中找到第一个月的日期。
e.g。列表有明显的日期
es6
那么它应该返回低于输出
15/5/2017,
3/5/2017,
7/4/2017,
4/4/2017,
1/4/2017,
31/3/2017,
22/3/2017,
5/3/2017,
2/3/2017
这就是我所做的
3/5/2017,
1/4/2017,
2/3/2017
有更好的方法吗?
答案 0 :(得分:1)
使用实体框架:
var lstFirstDayOfMonth = lstDate.GroupBy(d => d.Month).Select(g => g.OrderBy(x => x.Day).First()).ToList();
答案 1 :(得分:0)
评论中的解释。
public class Program
{
public static void Main(string[] args)
{
var dates = new List<DateTime>();
dates.Add(new DateTime(2017, 5, 15));
dates.Add(new DateTime(2017, 5, 3));
dates.Add(new DateTime(2017, 4, 7));
dates.Add(new DateTime(2017, 4, 4));
dates.Add(new DateTime(2017, 4, 1));
dates.Add(new DateTime(2017, 3, 31));
dates.Add(new DateTime(2017, 3, 22));
dates.Add(new DateTime(2017, 3, 5));
dates.Add(new DateTime(2017, 3, 2));
var firstOfEachMonths = dates
// Group the dates by their month.
.GroupBy(date => date.Month)
// Project each group into the earliest day.
.Select(group => group
.OrderBy(date => date.Day)
.First())
.ToList();
/*
* Output:
* 03.05.2017 00:00:00
* 01.04.2017 00:00:00
* 02.03.2017 00:00:00
*/
foreach (var firstOfEachMonth in firstOfEachMonths)
{
Console.Out.WriteLine(firstOfEachMonth);
}
}
}