Error when performing query with Linq Groupby in C#

Asked

Viewed 31 times

1

I need to select the Groups previously registered, bringing data not repeated. However, an error is returned when performing the query in the table Point of Attendance, where the countryside Group in which the GroupBy contains null value. How to adjust the code so that it returns no error if the field Group be empty?

OrigemDados = new OrigemDados(
    pontoAtendimentoService
        .RecuperarTodos(httpContextAccessor.HttpContext.User)
        .Select(pontoAtendimento => new { pontoAtendimento.Id, pontoAtendimento.Grupo })
        .GroupBy(p => p.Grupo)
        .Select(grp => grp.First())
        .ToList()
        .AsQueryable(),
    pontoAtendimento => pontoAtendimento
        .GetType()
        .GetProperty("Grupo")
        .GetValue(pontoAtendimento)
        .ToString(),
    mapeapeamento);

1 answer

2


Response to the problem presented:

Include a condition that you do not consider when the field Group contain a null value.

.Where(p => p.Grupo != null)

OrigemDados = new OrigemDados(
    pontoAtendimentoService
        .RecuperarTodos(httpContextAccessor.HttpContext.User)
        .Select(pontoAtendimento => new { pontoAtendimento.Id, pontoAtendimento.Grupo })
        .Where(p => p.Grupo != null)
        .GroupBy(p => p.Grupo)
        .Select(grp => grp.First())
        .ToList()
        .AsQueryable(),
    pontoAtendimento => pontoAtendimento
        .GetType()
        .GetProperty("Grupo")
        .GetValue(pontoAtendimento)
        .ToString(),
    mapeapeamento);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.