4
\$\begingroup\$

Curious if there is a better way to write a repository method that receives argument List<int> and checks if the database Contains an int?.

public List<int> GetNumbersByNumbers(IEnumerable<int> numbers)
{
    var convertedNumbers = numbers.Select(m => (int?)m);
    return Context.TblNumbers
        .Where(m => convertedNumbers.Contains(m.Number))
        .Select(m => m.Number.GetValueOrDefault())
        .ToList();
}
\$\endgroup\$
6
\$\begingroup\$

Another way to do this is to remove NULL values from the comparison to begin with, like so:

return Context.TblNumbers
              .Where(m => m.Number != null)
              .Where(m => convertedNumbers.Contains(m.Number.Value))
              .Select(m => m.Number.Value)
              .ToList();

I think this also reads more naturally since you only have the chance to match on non-null values anyway, instead of GetValueOrDefault() which implies you might need to get a default value.

\$\endgroup\$
  • 1
    \$\begingroup\$ Since you use the actual value m.Number.Value there's no need to convert the numbers to convertedNumbers anymore. \$\endgroup\$ – t3chb0t Jun 16 '16 at 12:29
1
\$\begingroup\$

If you want the method to behave the exact same way, then no. Since your table accepts nulls, even though your method signature only deals with non-nullable value types, you still have to map to a collection of nullable ints when using Contains.

By the way, it may be more efficient to call .ToList() and then select using GetValueOrDefault() depending on how the provider translates GetValueOrDefault() to SQL.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.