使用linq将列表或订单日期分成几周 [英] Split a list or ordered dates into weeks using linq
本文介绍了使用linq将列表或订单日期分成几周的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[3月2日,3月6日,3月7日,3月26日]
>的列表。本周开始周六和周日结束。
我想得到以下结果:
pre $ code $ Mar $ 6 $ b $ Mar 6 Mar 7
$ [$ 26
我怎样才能用LINQ做到这一点?您可以在 DateTime
上使用以下内容: >
Calendar.GetWeekOfYear方法(DateTime,CalendarWeekRule,DayOfWeek)
$ b
返回
时间
$ b包含指定
DateTime值中的日期
$ b
- 类型:
System.DateTime
- 日期和时间值。
规则
$ b类型:
System.Globalization.CalendarWeekRule
- 定义日历周的枚举值。
ul>
firstDayOfWeek
- 类型:
System.DayOfWeek
- 枚举值e代表每周的第一天。
给定
List< DateTime> myAwesomeList;
用法
var result = myAwesomeList.GroupBy(x =>
CultureInfo.CurrentCulture.Calendar
.GetWeekOfYear(x.date,
CalendarWeekRule.FirstDay,
DayOfWeek.Saturday))
.Select(grp => grp.ToList())
.ToList();
退货
列表与LT;列表与LT; DateTime的>>
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.
解决方案
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>>
这篇关于使用linq将列表或订单日期分成几周的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文