Nullreferenceexception error in Join

Asked

Viewed 58 times

0

I created a Join in LINQ to create a List:

(from p in listaProcedimento
    join pd in oListaprocedimentodetalhe on p.codigo equals pd.codigoProcedimento into pd1
    from pd2 in pd1.DefaultIfEmpty()
    select new ProcedimentoDetalhe()
    {
        codigoDetalhe = pd2.codigoDetalhe == null ? "000" : "012",
        codigoProcedimento = p.codigo,
        descricao = p.descricao,
        idadeMax = p.idadeMax,
        idadeMin = p.idadeMin
    }).OrderBy(p => p.descricao)
      .ToList();

I get the mistake by saying pd2 was null, being that I have already tried to correct this in line: pd2.codigoDetalhe == null ? "000" : "012".

Because it’s not working?

3 answers

3


I’m finding this code strange, but you’re not doing what you think you’re doing. You’re not analyzing whether the p2 is null is analyzing if a field of it (pd2.codigoDetalhe) is null, which is too late because the p2 is null and already gives error and cannot analyze its field that does not exist since it would be a field of something null. The correct would be:

codigoDetalhe = pd2 == null ? "000" : "012",

Still I do not know if this is the final solution, but it solves the question that is in the question.

Can you ensure that the field is never null? If you can’t you have to check it too, so:

codigoDetalhe = pd2 == null || pd2.codigoDetalhe == null ? "000" : "012",

I put in the Github for future reference.

  • You didn’t because you’re just listed the codes where pd2 == "012". I’ll post the classes to detail the question

  • 2

    Exactly what I said, you asked a question, solved this problem, received 3 answers, now want to change the question and invalidate the 3 answers, can not.

  • I get it, I’m gonna ask another question then

2

For what is void is the pd2, not the property pd2.codigoDetalhe.

Try it like this:

codigoDetalhe = pd2 == null ? "000" : "012",
  • You didn’t because you’re just listed the codes where pd2 == "012". I’ll post the classes to detail the question

1

Change your line to compare pd2 and code

codigoDetalhe = pd2 == null && pd2.codigoDetalhe == null ? "000" : "012",

A curious thing is that you change the code value.

If you’re messing with lists would do something more performatic like this.

(from p in listaProcedimento
    select new ProcedimentoDetalhe()
    {
        codigoDetalhe = (oListaprocedimentodetalhe.any(pd => p.codigo == pd.codigoProcedimento && pd.codigoDetalhe != null) ? "012" : "000" ,
        codigoProcedimento = p.codigo,
        descricao = p.descricao,
        idadeMax = p.idadeMax,
        idadeMin = p.idadeMin
    }).OrderBy(p => p.descricao)
      .ToList();

Inside your select would check your field .

(oListaprocedimentodetalhe.any(pd => p.codigo == pd.codigoProcedimento && pd.codigoDetalhe ! null)

Browser other questions tagged

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