多条件: //pivot 用过的年假
var queryVw = from C in query
group C by new { C.EmployeeID } into
D
select new
{
EmployeeID = D.Key.EmployeeID,
LeaveAnnualLeaves = D.Where(P => P.LeaveType == LeaveAnnualLeaves).Sum(P => (decimal?)P.LeaveDays) ?? 0,
AnnaulLeaves = D.Where(P => P.LeaveType == AnnualLeave).Sum(P => (decimal?)P.LeaveDays) ?? 0,
BenifitLeaves = D.Where(P => P.LeaveType == BenifitLeave).Sum(P => (decimal?)P.LeaveDays) ?? 0
};
嵌套: static void Main(string[] args)
{
var m = new []{
new S{Year = 2000, Month = 1, Day = 10},
new S{Year = 2000, Month = 2, Day = 10},
new S{Year = 2010, Month = 1, Day = 1},
new S{Year = 2010, Month = 2, Day = 1},
new S{Year = 2010, Month = 1, Day = 2},
new S{Year = 2010, Month = 2, Day = 2},
new S{Year = 2000, Month = 1, Day = 2},
new S{Year = 2000, Month = 2, Day = 2},
};
var q2 =
from s in m
group s by s.Year into YearGroup
select new
{
Year = YearGroup.Key,
MonthGroups =
from s2 in YearGroup
group s2 by s2.Month into MonthGroup
select new
{
Month = MonthGroup.Key,
Days =
from s3 in MonthGroup
orderby s3.Day
select s3.Day
}
};
var q = m.GroupBy(
s => s.Year,
(Year, YearGroup) => new
{
Year,
MonthGroups =
YearGroup.GroupBy(
s2 => s2.Month,
(Month, MonthGroup) => new
{
Month,
Days = MonthGroup.OrderBy(s3 => s3.Day).Select(s3 => s3.Day)
}
)
}
);
foreach (var elem in q)
//foreach (var elem in q2)
{
Console.WriteLine("Year = {0}", elem.Year);
foreach (var elem2 in elem.MonthGroups)
{
Console.WriteLine("\tMonth = {0}", elem2.Month);
foreach (var day in elem2.Days)
Console.WriteLine("\t\tDay = {0}", day);
}
}
}
}
}
//Year = 2000
// Month = 1
// Day = 2
// Day = 10
// Month = 2
// Day = 2
// Day = 10
//Year = 2010
// Month = 1
// Day = 1
// Day = 2
// Month = 2
// Day = 1
// Day = 2
本文介绍了一个使用 C# 中 LINQ 进行复杂分组查询的例子,包括多级分组和条件筛选。展示了如何根据员工 ID 对休假记录进行分组,并计算不同类型休假天数的总和。此外,还提供了一个嵌套分组查询的例子,按年份、月份对日期进行分组。

被折叠的 条评论
为什么被折叠?



