【问题标题】:Query For Linq Count查询 Linq 计数
【发布时间】:2014-08-02 07:39:30
【问题描述】:

任何人都可以将此查询翻译成 Linq 吗?此查询计算员工的出席次数。

select 
    count(attandance.empid),
    employee2.empname 
from 
    employee2
inner join 
    attandance 
    on employee2.empid=attandance.empid
group by 
    employee2.empname

【问题讨论】:

  • 你尝试了什么?如果您不了解 LinQ,请学习它或聘请可以为您做这件事的人。这个网站是为了在自己尝试之后获得帮助
  • 请查看我的意思的代码。我为此做了一个说明。还有一件事你知道谁写了上面的查询吗??

标签: c# mysql asp.net linq


【解决方案1】:

这应该会得到与 sql 相同的结果。如果您使用的是 linq to sql 或 EF,只需将这两个 List 替换为您的数据源即可。

        List<Employee2> employee2 = new List<Employee2>
        {
            new Employee2 { EmpId = 1, EmpName = "Bob" },
            new Employee2 { EmpId = 2, EmpName = "Sam" },
            new Employee2 { EmpId = 3, EmpName = "Jim" },
        };

        List<Attendance> attandance = new List<Attendance>
        {
            new Attendance { EmpId = 1 },
            new Attendance { EmpId = 2 },
            new Attendance { EmpId = 2 },
            new Attendance { EmpId = 3 },
            new Attendance { EmpId = 3 },
            new Attendance { EmpId = 3 },
        };

        var r = from emp in employee2
                join att in attandance on emp.EmpId equals att.EmpId
                group emp by emp.EmpName into g
                select new { EmpName = g.Key, Count = g.Count() };

【讨论】:

    【解决方案2】:

    这应该可行:

    var attendance = (from e in db.employee2 // db would be your datacontext
                      select new 
                      {
                         empName = e.empname,
                         attendanceCount = (from a in db.attandance
                                            where a.empid == e.empid).Count()
                      });
    

    如果你不想使用数据上下文,你可以通过连接数据源来尝试linqpad中的上述linq。

    【讨论】:

    • 工作!!谢谢好友。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 2016-11-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多