2012-03-28 63 views
1

如何將此TSQL查詢轉換爲LINQ To SQL?如何在LINQ To SQL中使用.Count()?

Select p3.Alias, Count(p3.Alias) as [Count] from Persons p1 
INNER JOIN Addresses a ON p1.Id  = a.Person 
INNER JOIN Persons  p2 ON a.CityX  = p2.Id 
INNER JOIN ContrAgents ca ON p2.Id  = ca.Slave 
INNER JOIN Persons  p3 ON ca.Master = p3.Id 
where p1.Type >9 and p1.Type<16 
group by p3.Alias 

我想兩兩件事:data在p3.Alias和p.Count()data

List<cNumberOfObject> number = (from p1 in vt.Persons 
              join a in vt.Addresses on p1.Id  equals a.Person 
              join p2 in vt.Persons  on a.CityX equals p2.Id 
              join ca in vt.ContrAgents on p2.Id  equals ca.Slave 
              join p3 in vt.Persons  on ca.Master equals p3.Id 
              where p1.Type>9 && p1.Type<16 
              group p3 by p3.Alias into p 
              select new cNumberOfObject 
              { 
               // Subject = p3.Alias, 
               Number = p.Count() 

              }).ToList(); 

回答

0

一個group by的結果是一個IGrouping。您可以通過訪問IGrouping上的Key屬性來訪問您分組對象的列的值:

var number = (from p1 in vt.Persons 
       join a in vt.Addresses on p1.Id  equals a.Person 
       join p2 in vt.Persons  on a.CityX equals p2.Id 
       join ca in vt.ContrAgents on p2.Id  equals ca.Slave 
       join p3 in vt.Persons  on ca.Master equals p3.Id 
       where (p1.Type > 9 && p1.Type < 16) 
       group p3 by p3.Alias into p 
       select new cNumberOfObject 
       { 
        Subject = p.Key, // The alias 
        Number = p.Count() 
       }).ToList()