gpt4 book ai didi

c# - 我如何从通用日期列表中选择不同的(按唯一的月份/年份)?

转载 作者:行者123 更新时间:2023-11-30 18:57:17 26 4
gpt4 key购买 nike

因此不同是基于唯一的月/年,而不仅仅是一个不同的月份(所以我希望 2011 年 1 月和 2012 年 1 月是不同的)

 // Test set of data
List<DateTime> CompleteListOfDates = new List<DateTime>();
CompleteListOfDates.Add(new DateTime(2011, 1, 1));
CompleteListOfDates.Add(new DateTime(2011, 1, 5));
CompleteListOfDates.Add(new DateTime(2011, 3, 1));
CompleteListOfDates.Add(new DateTime(2011, 5, 1));
CompleteListOfDates.Add(new DateTime(2011, 5, 1));
CompleteListOfDates.Add(new DateTime(2012, 1, 1));
CompleteListOfDates.Add(new DateTime(2012, 2, 1));

List<DateTime> UniqueMonthYears = new List<DateTime>();

/* need distinct list of DateTimes that are distinct by Month and Year and should be in UniqueMonthYears
For example:
new DateTime(2011, 1, 1)
new DateTime(2011, 3, 1)
new DateTime(2011, 5, 1)
new DateTime(2012, 1, 1)
new DateTime(2012, 2, 1)
*/

最佳答案

List<DateTime> result = source
.Select(d => new DateTime(d.Year, d.Month, 1))
.Distinct()
.ToList();

也很有用:

ILookup<DateTime, Order> ordersByMonth = ordersSource
.ToLookup(order => new DateTime(order.OrderDate.Year, order.OrderDate.Month, 1));

关于c# - 我如何从通用日期列表中选择不同的(按唯一的月份/年份)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8730045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com