I have the following query:
Get list of required team ids from DB:
IList<int> teamIds = (from sector in DbContext.sectors where sector.Type=typeValue group sector by sector.TeamId into teamSectors 开发者_如何学运维 select teamSectors.Key ).ToList();
Using this list fetch all sectors for required teams:
IList<InfrStadSector> sectorsForAllTeams = (from sector in DbContext.sectors where teamIds.Contains(sector.TeamId) select sector ).ToList();
Create list of Stadiums based on sectors:
IList<InftStadium> stadiums = new List<InfrStadium>(); foreach(int teamId in teamIds) { IList<InfrStadSector> teamSectors = sectorsForAllTeams.Where(sect=>sect.TeamId==teamIds).ToList(); stadiums.Add(new InfrStadium(teamId, teamSectors); }
My concern here is that for collection received from DB I need to apply Where/ToList on the client side once per each team
Is there any way to optimize that?
Thanks.
P.S. Potentially, I could sort items on server (using index), then sort teamIds and work with sectors collection without really 'querying' collection... but probably there is a better way to optimize that?
I think you can do this in one step.
var stadiums = DbContext.sectors
.Where( s => s.Type == typeValue )
.ToLookup( s => s.TeamId )
.Select( l => new InfrStadium( l.Key, l.ToList() )
.ToList();
Although, it would be better if you could have the constructor for InfrStadium
take an IEnumerable<Sector>
rather than requiring a List<Sector>
, then you could omit the extra ToList
.
精彩评论