用于通过休假类型查找总休假组的linq查询

时间:2014-03-30 11:26:22

标签: c# linq

我有1个员工休假表,其中包含以下记录:

empid          leave_type         Leave_from    Leave_to           leave_taken              status  
 1            annual leave         3-3-2014     4-3-2014               2                   approved

 1            annual leave         5-3-2014     6-3-2014               2                   approved

 1            sick leave           10-3-2014    11-3-2014              2                   approved

 1            sick leave           12-3-2014    13-3-2014              2                   approved

 1            Casual leave         19-3-2014    20-3-2014              2                   approved

 1            Casual leave         22-3-2014    23-3-2014              2                   approved

现在我想计算特定员工的休假总数,只有行军月份的休假类型,其状态如下所示:

leave_type        leave_taken

   annual leave           4

   sick leave             4

   casual leave           4

我写了这样的查询:

var data = (from r in context.emp_leaves
                            where r.Emp_id == empid && r.status == "Approved" 
                            group r by new
                            {
                                r.Emp_id,r.leave_type
                            } into g
                            select new
                            {
                                leave_taken = g.Sum(x => x.leave_taken)
                            });

但显示输出错误。

任何人都可以为我提供linq查询???

1 个答案:

答案 0 :(得分:0)

由于您要按Emp_id进行过滤,因此无需对其进行分组

var data = (from r in context.emp_leaves
            where r.Emp_id == empid && r.status == "Approved" 
            group r by r.leave_type into g
            select new
            {
              leave_type = g.Key,
              leave_taken = g.Sum(x => x.leave_taken)
            });