因此不同是基于唯一的月/年,而不仅仅是一个不同的月份(所以我希望 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/