C#数据表:添加缺少的日期

本文关键字:日期 添加 数据表 | 更新日期: 2023-09-27 18:26:46

我有一个具有以下结构的DataTable:

表结构

我想做的是,对于每个用户名,我都必须填写整个月的"Logdate"列的空白,就像上表中一样,用户名"Test"应该有从2015年1月12日到2015年12月31日的条目,销售值为0,因为这个月已经有两个条目,不应该添加。

C#数据表:添加缺少的日期

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Username", typeof(string));
            dt.Columns.Add("Logdate", typeof(DateTime));
            dt.Columns.Add("Sale", typeof(decimal));
            dt.Rows.Add(new object[] { "Test", DateTime.Parse("12/03/2015"), 4.5 });
            dt.Rows.Add(new object[] { "Test", DateTime.Parse("12/13/2015"), 15 });
            dt.Rows.Add(new object[] { "Test2", DateTime.Parse("12/18/2015"), 3 });
            dt.Rows.Add(new object[] { "Test2", DateTime.Parse("12/25/2015"), 40 });
            Dictionary<string, List<DataRow>> dict = dt.AsEnumerable()
                .GroupBy(x => x.Field<string>("UserName"), y => y)
                .ToDictionary(x => x.Key, y => y.ToList());
            foreach (string key in dict.Keys)
            {
                List<int> days = dict[key].Select(x => x.Field<DateTime>("Logdate").Day).OrderBy(x => x).ToList();
                int month = dict[key].Select(x => x.Field<DateTime>("Logdate").Month).FirstOrDefault();
                int year = dict[key].Select(x => x.Field<DateTime>("Logdate").Year).FirstOrDefault();
                int lastDay = (new DateTime(year, month, 1)).AddMonths(1).AddDays(-1).Day;
                for (int day = 1; day <= lastDay; day++)
                {
                    if(!days.Contains(day))
                    {
                       dt.Rows.Add(new object[] { key, new DateTime(year, month, day), 0 });
                    }
                }
            }
        }
    }
}
​