Split a list or ordered dates into weeks using linq [closed]

拥有回忆 提交于 2019-12-23 06:58:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!