结合2个linq查询 - 分组和连接

时间:2013-05-13 10:56:56

标签: c# linq linq-to-entities

我的Db中有2个单独的表供客户及其相关种族使用。 customers表包含种族的外键ID。我想创建一个Linq查询,显示每个种族的总数以用于报告目的。例如......

 +------------+------------------+
 |  Ethnicity | Customer Count   |
 +------------+------------------+
 |  White     |   100            |
 +------------+------------------+
 |  Black     |   50             |
 +------------+------------------+
 |  Chinese   |   20             |
 +------------+------------------+ etc...

到目前为止,我有以下两个LINQ查询:

var customers = repository.GetAll<Customer>();
var ethnicities = repository.GetAll<Ethnicity>();

var query1 = customers.GroupBy(c => c.EthnicityId).Select(g => new { Key = g.Key, Count = g.Count() });

查询1显示总计但使用种族ID而不是文本(EthnicityType)。

var query2 = from c in customers
             join e in ethnicities on c.EthnicityId equals e.Id
             where (c.EthnicityId == e.Id)
             select new { Ethnicity = e.EthnicityType, Count = ??? };

查询2加入两个表但是如何对此进行分组以便获取Total而不是单个记录?希望这是有道理的,希望对此有所帮助。

3 个答案:

答案 0 :(得分:1)

var query2 = query1.Join(ethnicities, x => x.Key, 
                                      y => EthnicityId, 
                                   (x, y) => new { Ethnicity = y.EthnicityType, 
                                                      Count = x.Count });

答案 1 :(得分:1)

有很多方法可以做你想要的,但如果种族数量很少,你可以在客户端创建一个查找表,并使用它来将ID映射到描述性名称:

var customers = repository.GetAll<Customer>();
var ethnicities = repository.GetAll<Ethnicity>().ToDictionary(e => e.Id);

var query1 = customers
  .GroupBy(c => c.EthnicityId)
  .Select(g => new { Key = ethnicities[g.Key], Count = g.Count() };

ToDictionary(e => e.Id)用于创建字典映射ID到名称,然后字典用于使用ethnicities[g.Key]查找名称。

答案 2 :(得分:0)

我认为这可行:

var query2 = 
    from e in ethnicities
    join c in customers on e.Id equals c.EnthnicityId
    into g
    where g.Any()
    select new { Ethnicity = g.First(), Count = g.Count() };