Is there a LINQ method that returns a default value of my preference?

Asked

Viewed 84 times

1

Is there any LINQ method that returns a default value of my preference, which fulfills the role of this method in a more efficient way?

public static int? procurarIdPorCpf(string cpf)
{
    using (Contexto context = new Contexto())
    {
        if (context.pessoaFisica.Any(p => p.CPF.Equals(cpf)))
            return context.pessoaFisica.First(p => p.CPF.Equals(cpf)).ID;
        else
            return null;
    }
}
  • What would be "more efficient" in your view? A more succinct syntax?

2 answers

4


Use the null coalescence operator:

return context.pessoaFisica.FirstOrDefault(p => p.CPF.Equals(cpf)) ?? meuValorDefault;

As you indicated you want the ID, you could do so:

return context.pessoaFisica
              .Where(p => p.CPF.Equals(cpf))
              .Select(p => (int?)p.Id)
              .FirstOrDefault();

In this case the operator is not required ??, because the value of Firstordefault will already be null if there is no record.

  • You can add a brief explanation regarding this operator?

  • In the test I did there was an error saying that such an operator cannot be using between an int type and a null.

  • I did a quick search on the operator. From what I saw, it returns the value on the right side if the value on the left side is null. If that’s right, it doesn’t fit in such situation... My ID is a non null int.

  • In case the type has to be nullable to function: a class or a type such as int?.

  • I edited the answer.

  • The second example worked correctly, thank you

  • I won a free down-vote?

  • Perhaps by the lack of observation of the first example, because it returns to me a physical person and not an integer.

  • I tested my method and the two responses on https://dotnetfiddle.net/ and that response was far faster.

Show 4 more comments

1

It is better to go through the enumeration only once:

    public static int? procurarIdPorCpf(string cpf)
    {
        using (Contexto context = new Contexto())
        {
            var pessoa = context.pessoaFisica.FirstOrDefault(p => p.CPF.Equals(cpf));
            return pessoa == null ? null : pessoa.ID;
        }
    }
  • It’s just that I didn’t want to select the person themselves, just one of their properties, I thought that the way I did it would be better, because I do it with thousands of records and I didn’t want to instantiate thousands of personal objects. But I take this opportunity to ask and ask a question, from?

Browser other questions tagged

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