这可能有效(或至少给您一个想法):
var monthEmpGroups = tblEmpJobs.AsEnumerable()
.Select(r => new
{
Row = r,
Employee = r.Field<String>("Employee"),
Year = r.Field<DateTime>("Date").Year,
Month = r.Field<DateTime>("Date").Month
})
.GroupBy(x => x.Employee);
DataTable tblMonthResultJob1 = new DataTable();
tblMonthResultJob1.Columns.Add("Employee", typeof(string));
var dtf = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
foreach (var empGroup in monthEmpGroups)
{
string employee = empGroup.Key;
var newRow = tblMonthResultJob1.Rows.Add();
newRow["Employee"] = employee;
var empMonthGroup = empGroup.GroupBy(mg => new { mg.Year, mg.Month });
foreach (var empYearMonthGroup in empMonthGroup)
{
int year = empYearMonthGroup.Key.Year;
int month = empYearMonthGroup.Key.Month;
string colName = string.Format("{0} {1}", dtf.GetMonthName(month), year);
if (!tblMonthResultJob1.Columns.Contains(colName))
tblMonthResultJob1.Columns.Add(colName, typeof(int));
int empJob1Count = empYearMonthGroup.Sum(x => x.Row.Field<int>("Job1"));
newRow[colName] = empJob1Count;
}
}
// do the same for the other job types
更新如果您需要在“结束”处添加“总行”,如评论:
DataRow totalRow = tblMonthResultJob1.Rows.Add();
totalRow["Employee"] = "ALL";
var monthGroups = tblEmpJobs.AsEnumerable()
.Select(r => new {
Row = r,
Year = r.Field<DateTime>("Date").Year,
Month = r.Field<DateTime>("Date").Month
})
.GroupBy(x => new { x.Year, x.Month });
foreach (var monthGroup in monthGroups)
{
int yearAll = monthGroup.Key.Year;
int monthAll = monthGroup.Key.Month;
string colName = string.Format("{0} {1}", dtf.GetMonthName(monthAll), yearAll);
if (!tblMonthResultJob1.Columns.Contains(colName))
tblMonthResultJob1.Columns.Add(colName, typeof(int));
int allJob1Count = monthGroup.Sum(x => x.Row.Field<int>("Job1"));
totalRow[colName] = allJob1Count;
}
更新2
我在这一行 int 上收到错误 system.dbnull
empJob1Count = empYearMonthGroup.Sum(x => x.Row.Field<int>("Job1"));
我认为有一些空值,并且在求和时无法转换空值。请帮忙,我应该如何解决这个问题
您可以使用此代码将 an 默认int?
为零:
var empYearMonthCount = empYearMonthGroup.Sum(x =>
{
int? job1 = x.Row.Field<int?>("Job1");
int value = 0;
if(job1.HasValue) value = job1.Value;
return value;
});