# Linq-to-Sql Contains an int? inside a list of int

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();
}


## 2 Answers

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.

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

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.