0

Linq をエンティティに使用する count コマンドに関して問題があります。私がやりたいことは、すべての性別を私の従業員の市民ステータスで数えることです。

市民のステータス 0 - all ; 1 = single ; 2 - married

私はエンティティへのlinqの初心者です。ここに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 に答える