C# 将数据表按周分组
我想将我的C# 将数据表按周分组,c#,linq,C#,Linq,我想将我的DataTable按周分组,并将其显示在DataGridView中 这是我的密码: var week = dt.AsEnumerable().GroupBy(row => Convert.ToDateTime(row["Date"])) .Select(g => new { Date = g.Key.ToString(), }).ToList(); dat
DataTable
按周分组,并将其显示在DataGridView
中
这是我的密码:
var week = dt.AsEnumerable().GroupBy(row => Convert.ToDateTime(row["Date"]))
.Select(g => new
{
Date = g.Key.ToString(),
}).ToList();
dataGridView1.DataSource = week;
您可以使用以下内容:
private static string[] TimeBucket = { "0D", "1D", "1W", "2W", "1M", "2M", "3M", "6M", "9M", "1Y", "2Y", "3Y", "5Y", "10Y", "15Y", "20Y", "25Y", ">=30Y" };
private static int[] TimeIntervals = { 0, 1, 7, 2 * 7, 30, 2 * 30, 3 * 30, 6 * 30, 9 * 30, 365, 2 * 365, 3 * 365, 5 * 365, 3650, 15 * 365, 20 * 365, 25 * 365, 30 * 365 };
private static string ComputeMaturity(DateTime? mat, DateTime? refDate)
{
if (!mat.HasValue)
return "Void";
int nbd = (mat - refDate).Value.Days;
for (int pos = 0; pos < TimeBucket.Length; pos++)
if (nbd < TimeIntervals[pos])
return TimeBucket[pos];
return TimeBucket[(TimeBucket).Length - 1];
}
您可以使用
System.Globalization
命名空间,使用您想要的规则来查找日期时间
的一年中的一周:
using System.Globalization;
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
var week = dt.AsEnumerable().GroupBy(row =>
dfi.Calendar.GetWeekOfYear(Convert.ToDateTime(row["Date"]), dfi.CalendarWeekRule,
dfi.FirstDayOfWeek))
.Select(g => new
{
Date = g.First()["Date"].ToString(),
}).ToList();
在没有更多信息的情况下,我无法理解您的
选择与按周分组的关系,因此我只选择了每个组的第一个日期。那么,您的问题是什么?是否要将日期转换为每周时段?像“1W”、“2W”、“3W”等等?我的问题是,sir@S.Akbari是如何按周分组的?是的,sir@Skyuppercut请参考并更改处理数据表的逻辑您可以使用此答案定义自己的时间段,并将日期分组为这些时间段谢谢,Skyuppercut先生!我会试试这个Sir@Skyuppercut,我试过了,但是我的数据表没有分组。它只显示时间段,没有分组。先生,请帮帮我,现在可以了。我先分组,然后转换成桶。您应该先进行转换,然后进行分组。
using System.Globalization;
DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
var week = dt.AsEnumerable().GroupBy(row =>
dfi.Calendar.GetWeekOfYear(Convert.ToDateTime(row["Date"]), dfi.CalendarWeekRule,
dfi.FirstDayOfWeek))
.Select(g => new
{
Date = g.First()["Date"].ToString(),
}).ToList();