2013-05-13 83 views
0

我在客户和他们的相关种族的Db中有2个单独的表。 customers表包含种族的外键Id。我想创建一个Linq查询来显示报告中每个种族的总数。例如像...结合2 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联接两个表,但如何分组,这样我得到总,而不是单个记录?希望这是有道理的,希望能对此有所帮助。

回答

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

感谢。工作过一种享受! – 2013-05-13 12:34:36

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]查找名称。

+0

感谢您的信息马丁。 – 2013-05-13 12:51:39

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() };