HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

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

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
linqsqlcontainslistintinside

Problem

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

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

Solution

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.

Code Snippets

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

Context

StackExchange Code Review Q#110950, answer score: 8

Revisions (0)

No revisions yet.