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

1

Is there a LINQ method that returns a default value of my preference that fulfills the role of this method more efficiently?

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;
    }
}
    
asked by anonymous 17.07.2014 / 17:48

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 you do not need the ?? operator, since the value of FirstOrDefault will already be null if it has no records.

    
17.07.2014 / 17:54
1

It is best 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;
        }
    }
    
17.07.2014 / 18:21