How can I make a "tender" expression in a simpler way

Asked

Viewed 63 times

0

I don’t know a good way to ask this, I googled it but I didn’t think what I wanted, I know the expression variavel?.atributo which makes the code only try to catch the attribute if the variable has value, if it does not return null

I also know the expression variavel ?? 0 which causes the code to return 0 value after the ?? if the value is null

The point is, I’ve seen codes where these two are used together, but in my code I end up getting a null exception.

An example of my current code:

var notaComp = notasFiltradas?.Where(x => x.TipoAvaliacao == (int)TipoAvaliacaoParcial.AutoAvaliacao)?.SingleOrDefault().Nota ?? 0;
  • See in the null exeption description which field is null.

  • the enumeration did not generate results, it is this part here that comes before var notasFiltradas = Model.Notas.Where(x => x.Idcompetencia == competencia.Idcompetencia)

  • There’s nothing ternary in this code.

2 answers

0


After more google searches I found a suggestion that worked, just change the SingleOrDefault for FirstOrDefault, thus falling into the ternary expression ??

var notaComp = notasFiltradas?.Where(x => x.TipoAvaliacao == (int)TipoAvaliacaoParcial.AutoAvaliacao)?.FirstOrDefault().Nota ?? 0;

0

You can reduce the condition of your "Where" to inside Firstordefault in this way:

var notaComp = notasFiltradas?.FirstOrDefault(x => x.TipoAvaliacao == (int)TipoAvaliacaoParcial.AutoAvaliacao)?.Nota ?? 0;

It will work the same way, but you will save a bit of code if Firstordefault() does not return any value, the ? will not allow access to the Note property, and will return 0;

Browser other questions tagged

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