开发者

Linq2Sql: query optimisation

开发者 https://www.devze.com 2023-02-04 03:30 出处:网络
I have the following query: Get list of required team ids from DB: IList<int> teamIds = (from sector in DbContext.sectors

I have the following query:

  1. 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();
    
  2. 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();
    
  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消