我希望我正确地理解了你。
给定一堆日期,按一年中的星期分组:
// some testdata
var datesList = Enumerable.Range(0, 8).Select (e => DateTime.Now.AddDays(7 * e)).ToList();
Func<DateTime, int> weekProjector = d =>
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
var weeks = datesList.GroupBy(weekProjector).ToList();
你应该通过这个查询得到你想要的结果:
var result = weeks.OrderBy(w => w.Key)
.Select((g, i) => new {WeekType = (i / rotation) % 2, Week = g})
.GroupBy(w => w.WeekType)
.ToList();
rotation
您的“轮换”(2
或4
)在哪里,并且是2
您想要的组数(组A
和B
=> 2组)。
您可能想添加到 aSelect
之后GroupBy
以仅选择您想要的数据,例如:
var weekA = result.Where(r => r.Key==0).Select(g => g).SelectMany(g => g).SelectMany(a => a.Week).ToList();
var weekB = result.Where(r => r.Key==1).Select(g => g).SelectMany(g => g).SelectMany(a => a.Week).ToList();
一个更具可读性/通用的解决方案:
void Rotate<TResult, TGroup>(IEnumerable<TResult> datesList, Func<TResult, TGroup> grouper, int rotation, out List<TResult> listA, out List<TResult> listB)
{
listA = new List<TResult>();
listB = new List<TResult>();
var weeks = datesList.GroupBy(grouper).ToList();
var c_rotation = 0;
var c_list = listA;
using (var en = weeks.GetEnumerator())
while(en.MoveNext())
{
c_list.AddRange((IGrouping<TGroup, TResult>)en.Current);
c_rotation++;
if (c_rotation == rotation)
{
c_rotation = 0;
c_list = c_list == listA ? listB : listA;
}
}
}
像这样使用它:
List<DateTime> listA;
List<DateTime> listB;
Func<DateTime, int> weekProjector = d =>
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
Rotate(datesList, weekProjector, 2, out listA, out listB);