Laziale
Laziale

Reputation: 8225

Improving linq query with groupby and first()

I have a Linq query which I'm grouping and retrieving the first result, where I think the issue is happening and the query timeouts for larger amount of data:

This is the query:

var result = await base.GetAllPagedAndSortedQueryBuilder(input)
    .Include(x => x.Person)
    .WhereIf(input.EventId.HasValue, x => x.Race.EventId == input.EventId)
    .GroupBy(x => new { x.JuryRoleId, x.PersonId })
    .Select(s => new RaceJuryDto
    {
        Id = s.First().Id,
        Distance = s.Sum(r => Convert.ToDouble(r.Distance)).ToString(),
        PersonId = s.First().Person.Guid,
        Status = s.First().Status,
        JuryRoleId = s.First().JuryRoleId,
        JuryPersonId = s.First().Person.Id,
        CountRacesJury = s.GroupBy(s => s.JuryRoleId).Count(),
        AddressCity = s.First().Person.Address.City,
        RaceIds = s.Select(s => s.RaceId).ToList(),
        RaceJuryIds = s.Select(s => s.Id).ToList()
    }).ToListAsync();

It works 'okay' with not a lot of data but when we test against larger datasets is timing out. I think the issue is when calling the First() for each property.

What can I do about this and how can I improve the query?

Upvotes: 0

Views: 116

Answers (0)

Related Questions