int[] ServiceID
Don't call your local variable ServiceID
-
- local variables should be called in camelCase,
- variables representing sets should be plural,
- you have a property called ServiceID on your table - calling the local variable the same is a recipe for confusion
The pattern you need to ask is not "does my table.ServiceId contain these wanted serviceIDs", it's "do these wanted serviceIDs contain the table serviceID":
int[] wantedServiceIDs = {1, 4, 5}
var result = from table in _context.Table
where wantedServiceIDs.Contains(table.ServiceID)
In SQL terms, this will be translated to
FROM table
WHERE serviceId IN (1,4,5)
The confusion, in you're familiar with SQL, is that this is the flip of what you asked for ..
You're supposed to write a LINQ of list.Contains(column)
and SQL needs it flipped over to column IN(list)
- but of course, when you look at the english language it's logical - x Contains y is the flip of y IN x. Familiarity with SQL's IN, and that the english words "IN" and "Contains" themselves meaning virtually the same thing probably leads a lot of people to try column.Contains(list)
when what they need is the inverse
Another possible point of confsuon is that when people think about a column of data in an SQL table, they see multiple values.. But really the database/code only considers one row's worth of data at a time, so it's multiple.Contains(single)
or single IN (multiple)
, and never multipleX.Contains(multipleY)
You can also ask "are any of the wanted service ids equal to the table service id"
var result = from table in _context.Table where
wantedServiceIDs.Any(wantedId => table.ServiceID == wantedId)
This latter form is trickier, because it often leads you to believe you can use complex expressions to refine your table
, and you can't so I'd strive to avoid using it.. For example
var wantedServices = new[] { new Service{ ID = 1, name = ""}, new Service{ ID = 2, name = ""} };
//this wouldn't work/not be translatable to SQL
var result = from table in _context.Table where
wantedServices.Any(wantedService => table.ServiceID == wantedService.ID)
Using the simple "list of ID ints" .Contains discourages you from trying this form