0

我的数据库中有 2 个单独的表格,用于客户及其相关种族。客户表包含种族的外键 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 连接了这两个表,但是如何对它进行分组以便获得总计而不是单个记录?希望这是有道理的,不胜感激。

4

3 回答 3

1
var query2 = query1.Join(ethnicities, x => x.Key, 
                                      y => EthnicityId, 
                                   (x, y) => new { Ethnicity = y.EthnicityType, 
                                                      Count = x.Count });
于 2013-05-13T11:06:46.397 回答
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]

于 2013-05-13T11:08:16.893 回答
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() };
于 2013-05-13T11:21:40.607 回答