Reputation: 1291
I am trying to get the list of files (file is an entity) which has the selected services (service is another entity). The file can have many services.
I tried the following statement, but it does not give the correct results:
var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers
var resultsTemp = repository.Files.Where(f => f.Services.Select(s => s.ServiceTypeID).Intersect(_serviceTypes).Any());
What am I missing?
EDIT:
_serviceTypes in an array of integers: {int[2]}
The files can have many services, each of which as one service type id (integer)
For instance, a file has two services in it: ambulance (service type id: 3) and hospitalization (service type id: 5). I want to get all the files which have both the services in it.
Upvotes: 1
Views: 114
Reputation: 13438
Some of the following operations should answer your question:
// requested IDs
var requestedIDs = new List<int>();
// the IDs from one file
var IDsInFile = new List<int>();
if (requestedIDs.Except(IDsInFile).Any())
{
// at least some requested IDs are not in the file
}
else
{
// all requested IDs are in the file
}
if (requestedIDs.Intersect(IDsInFile).Any())
{
// at least some requested IDs are in the file
}
else
{
// not a single requested ID is in the file
}
Since you want every file that contains all of the requested services, the correct query would be
var _serviceTypes = viewModel.SelectedServiceTypes;
// _serviceTypes is an array of integers
var resultsTemp = repository.Files.Where(f => !_serviceTypes.Except(f.Services.Select(s => s.ServiceTypeID)).Any());
Upvotes: 1
Reputation: 5402
You're checking if a single element exists in both lists, which is probably not what you had in mind. Try to check if the intersection is equal to the smaller list (assuming it's _serviceTypes
, as that's not evident from your code):
var resultsTemp = repository.Files
.Where(f => f.Services.Select(s => s.ServiceTypeID)
.Intersect(_serviceTypes)
.OrderBy(x => x)
.SequenceEqual(_serviceTypes.OrderBy(x => x));
Upvotes: 0