在linq中使用groupby的多个连接

本文关键字:连接 groupby linq | 更新日期: 2023-09-27 18:02:36

我有5个表,我想使用linq获得一些信息。我正在使用以下查询从data读取数据。

var query = (from GRD in _tblStudents.GetQueryable() 
             join apt in _tblApplicants.GetQueryable() 
                  on GRD.ApplicantID equals apt.ApplicantID
             join cls in _tblClasses.GetQueryable() 
                  on GRD.CityID equals cls.ClassID
             join prg in _tblPrograms.GetQueryable() 
                  on cls.ProgramID equals prg.ProgramID
             join city in _tblCities.GetQueryable() 
                  on GRD.CityID equals city.CityID
             where GRD.AcademicYearID == yearId && cls.ProgramID == programId
             group apt by new{apt.Gender} into grouped
             select new CityWiseStudentModel
             {
                  CityName=city.CityName, 
                  //'city' does not exist in the current context
                  Gender = grouped.Count(),
                  programName=prg.Program, 
                 //'prg' does not exist in the current context
              }   
           );

如何从 City 表中获取城市名称和从prg

在linq中使用groupby的多个连接

获取程序名称

group <--> by <--> into <-->的范围更改为IGrouping<a,b>

我的意见是不仅apt.Gender是你的关键,而且city.CityNameprg.Program

试试这个(或类似的):

group apt by new{apt.Gender, city, prg} into grouped
select new CityWiseStudentModel
{
     CityName = grouped.Key.city.CityName, 
     Gender = grouped.Count(), //rename GenderCount
     programName = grouped.Key.prg.Program,
     // Gender = grouped.Key.Gender,
} 

请记住,grouped仅保存已分组的内容。如果您只对adt进行分组,那么cityprg将无法在您的select中使用。

所以你需要:

  1. 城市程序纳入grouped(否则不可用)
  2. 访问grouped 集合中的CityNameProgram

像这样的代码应该可以达到这个效果:

...
group new { apt, cls, prg, city } by new{apt.Gender} into grouped
select new CityWiseStudentModel
{
   CityNames = grouped.Select(g => g.city.CityName),  
   ...
   programNames = grouped.Select(g => g.prg.Program)
}