0

我对使用 Linq 到实体的计数命令有疑问。我想做的是用我员工的公民身份来计算所有性别

公民身份 0 - all ; 1 = single ; 2 - married

我是 linq to entity 的新手,这里是我在 SQL 命令上的代码。

我不知道我将如何转换这个。

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 名员工(男性和女性)我想知道其中有多少是单身或已婚。

谢谢。=)

4

2 回答 2

0

这个 linqpad 程序按公民身份对员工进行分组,然后计算所有成员以及男性和女性,我认为这表明了您所追求的分组。

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;}
}
于 2013-05-24T05:43:21.663 回答
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();
于 2015-07-16T11:49:00.757 回答