简体   繁体   中英

LINQ Query: new query object with a Count element of another table

Bellow is the LINQ query I am trying to operate

var custSelect = from m in _context.Entities
                         where m.Active == true && m.EntityTypeId == 1
                         orderby m.Name
                         select new { m.EntityId, m.Name, JobCount = _context.Jobs.Where(o => o.CustomerId == m.EntityId).Distinct().ToList().Count };

I want to be able to select a new selection variable as JobCount which is an integer counting how many jobs are attached to said customer. Then later, during the model creation, I want to be able to then order by the Count variable for example.

Is there any way to do this?

You can try this way, Here is the live demo

var result = (from e in entities
                  join j in jobs on e.EntityId equals j.CustomerId
                  where e.Active && e.EntityTypeId == 1
                  select new 
                  {
                      e.EntityId, 
                      e.Name,
                      j.JobId
                  }).GroupBy( p => new { p.EntityId, p.Name })
                    .Select(g => new 
                                {
                                    EntityId = g.First().EntityId, 
                                    Name = g.First().Name,
                                    JobCount = g.Count()  
                                })
                    .OrderBy(p => p.Name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM