查询中的datesList只是一个日期时间值列表。
使用linq查询/ groupby,我将属于该年某一周的所有日期分组为分组。
Func<DateTime, int> weekProjector = d =>
CultureInfo.CurrentCulture.Calendar.GetWeekOfYear( d, CalendarWeekRule.FirstDay, DayOfWeek.Monday);
var weeks = (from date in datesList group date by weekProjector(date.Date)).ToList();
假设星期集合包含8个星期,并且可以按A和B周旋转。这意味着如果用户以A周开始,则按值2的旋转会传递此结果:
A A,B B,A A,B B(8周,每周轮换2次) A A A A,B B B B(8周,每周轮换4次)如何在考虑旋转值(可以是1到8之间的任何数字)的情况下,将周集合和组/项目或任何日期时间值查询到单独的weekListA / weekListB中。
更新:
最终状态是2个列表A和B列表,每个列表包含来自周集合的日期时间值。
更新2:在此示例中,每周轮换将具有因子4:这意味着我有4周的A型,4周的B型等等
答案 0 :(得分:4)
我希望我能正确理解你。
给出一堆日期,按一年中的一周分组:
// 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
和{ {1}} =&gt; 2组)。
您可能希望在B
之后添加Select
以仅选择您想要的数据,例如:
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;
}
}
}
答案 1 :(得分:1)
这可能是您正在寻找的内容,GroupBy Index % 2
:
var abRotations = datesList
.GroupBy(d => CultureInfo.CurrentCulture.Calendar.GetWeekOfYear(d, CalendarWeekRule.FirstDay, DayOfWeek.Monday))
.Select((wg, i) => new { WeekGroup = wg, Index = i })
.GroupBy(x => x.Index % 2);
List<DateTime> A_Rotation = abRotations.First().SelectMany(x => x.WeekGroup).ToList();
List<DateTime> B_Rotation = abRotations.Last().SelectMany(x => x.WeekGroup).ToList();