问题
Say I have a list of 5 dates [Mar 2,Mar 6, Mar 7, Mar 26]
all in the year 2018.
The week start on Saturday and end Sunday.
I want the following result
[Mar 2]
[Mar 6, Mar 7]
[Mar 26]
How can I do it with LINQ? Or in a functional way.
回答1:
You can use the following on DateTime
Calendar.GetWeekOfYear Method (DateTime, CalendarWeekRule, DayOfWeek)
Returns the week of the year that includes the date in the specified DateTime value.
time
- Type:
System.DateTime
- A date and time value.
rule
- Type:
System.Globalization.CalendarWeekRule
- An enumeration value that defines a calendar week.
firstDayOfWeek
- Type:
System.DayOfWeek
- An enumeration value that represents the first day of the week.
Given
List<DateTime> myAwesomeList;
Usage
var result = myAwesomeList.GroupBy(x =>
CultureInfo.CurrentCulture.Calendar
.GetWeekOfYear(x.date,
CalendarWeekRule.FirstDay,
DayOfWeek.Saturday))
.Select(grp => grp.ToList())
.ToList();
Returns
List<List<DateTime>>
回答2:
I want to post this as an iterative answer since I don't want to introduce iterative bias thinking into the question since this might influence the elegant of the answer that I get :) So please don't read this if you understand the question being asked.
Here is a quick and dirty way to solve the problem using an iterative way.
var orders = new List<int> { 4, 5, 6, 0, 1, 2, 3 };
var nums = new List<int> {2, 5, 6, 2, 2, 4};
var queue = new Queue<int>(nums);
var results = new List<List<int>>();
while (queue.Count > 0)
{
var subLists = new List<int>();
foreach (var order in orders)
{
if(order == queue.Peek())
subLists.Add(queue.Dequeue());
if (queue.Count == 0)
break;
}
results.Add(subLists);
}
来源:https://stackoverflow.com/questions/49419279/split-a-list-or-ordered-dates-into-weeks-using-linq