将选择/计数SQL命令转换为Linq到实体

时间:2013-05-24 03:15:34

标签: sql select count linq-to-entities

我在使用Linq到实体的count命令问题上遇到了问题。 我想要做的是用员工 civilstatus 计算所有性别

civilstatus 0 - all ; 1 = single ; 2 - married

我是linq对实体的新手 这是我在SQL Command上的代码。

我不知道如何转换这个。

select '0' as UserID, COUNT(a.Gender) as TotalCount from Employees a 
union all
select '1' as UserID, COUNT(a.Gender) as TotalCount from Employees a where a.CivilStatus = 1
union all
select '2' as UserID, COUNT(a.Gender) as TotalCount from Employees a where a.CivilStatus = 2

喜欢这个

UserID | TotalCount
0     | 10
1     | 7
2     | 3

提示
假设我有10名员工(男性和女性)我想知道他们中有多少是单身或已婚。

感谢。 =)

2 个答案:

答案 0 :(得分:0)

这个linqpad计划按照Civil Status对员工进行分组,然后统计所有成员以及男性和女性,我认为这表明了您所追求的分组。

void Main()
{
    var employees = new employee[] { new employee {Id=1,CivilStatus=1, Gender='M'},
    new employee {Id=2,CivilStatus=1, Gender='M'},
    new employee {Id=3,CivilStatus=2, Gender='F'},
    new employee {Id=4,CivilStatus=1, Gender='F'},
    new employee {Id=5,CivilStatus=2, Gender='F'},
    new employee {Id=6,CivilStatus=1, Gender='M'},
    new employee {Id=7,CivilStatus=2, Gender='M'},
    new employee {Id=8,CivilStatus=2, Gender='M'},
    new employee {Id=9,CivilStatus=2, Gender='M'},
    new employee {Id=9, Gender='M'}};

    var result = from x in employees 
    group x by x.CivilStatus into g
    select new { CivilStatus = g.Key,
                    All=g.Count(), 
                    Male=g.Count(e => e.Gender=='M'), 
                    Female=g.Count(e => e.Gender=='F') } ;
    result.Dump();

}

class employee
{
    public int Id {get;set;}
    public int CivilStatus {get;set;}
    public char Gender {get;set;}
}

答案 1 :(得分:0)

试试这个:

var q1 = from a in context.Employees 

                    group a by 1 into g
            select new
            {
                UserID = 0,
                TotalCount = g.Count(),
            };
        var q2 = from a in context.Employees 
                 where a.CivilStatus = 1
                 group a by 1 into g
                 select new
                 {
                     UserID = 1,
                     TotalCount = g.Count(),
                 };
        var q3 = from a in context.Employees 
                 where a.CivilStatus = 2
                 group a by 1 into g
                 select new
                 {
                     UserID = 2,
                     TotalCount = g.Count(),
                 };
        var result = q1.Union(q2).Union(q3).ToList();