Reputation: 739
The code below userModel.Carriers
is the type of IEnumerable<CarrierModel>
.
userModel.Carriers
has a list of carriers having Ids. With those Ids, I want to get CarrierDivision usign linq. But, I can't get it right because linq sqlexpression is not compatible with IEnumerable expression
.
userModel.Carriers = carriersForRegion.Select(carrier => Mapper.Map<CarrierModel>(carrier))
.ToList();
var carrierDivision = from c in db.CarrierDivision where c.Contains();
Upvotes: 0
Views: 704
Reputation: 32445
collection.Contains
will generate .. WHERE CarrierId IN (1, 2, 3)
sql query
var carrierIds = userModel.Carriers.Select(carrier => carrier.Id).ToArray();
var divisions = db.CarrierDivision
.Where(division => carrierIds.Contains(division.CarrierId))
.ToArray();
In case db.CarrierDivision
returns IEnumerable
(not database), then I would suggest to create HashSet
of carrier ids.
var carrierIds = userModel.Carriers.Select(carrier => carrier.Id).ToHashSet();
var divisions = db.CarrierDivision
.Where(division => carrierIds.Contains(division.CarrierId))
.ToArray();
With HashSet
search executed without extra enumerations - O(1)
Upvotes: 1