按周对DataTable进行分组

时间:2018-04-30 07:30:29

标签: c# linq

我希望将我的DataTable分组几周,并将其显示在DataGridView

这是我的代码:

var week = dt.AsEnumerable().GroupBy(row => Convert.ToDateTime(row["Date"]))
              .Select(g => new
              {
                  Date = g.Key.ToString(),
              }).ToList();
dataGridView1.DataSource = week;

2 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

 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];
        }

在groupby期间,

var week = dt.AsEnumerable().GroupBy(row => ComputeMaturity(Convert.ToDateTime(row["Date"]),DateTime.Now))
              .Select(g => new
              {
                  Date = (g.Key),
              }).ToList();
dataGridView1.DataSource = week;

答案 1 :(得分:0)

您可以使用System.Globalization命名空间来查找DateTime的一周,并使用您想要的规则:

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();

我无法弄清楚你的Select如何与数周的分组相关而没有更多信息,所以我只选择了每个小组的第一个日期。