Reputation: 881
I need a linq call to return a list of floor id's in an array format so that I am able to use it to do a Contains call to return all the related data.
I can't get linq to return an array of floors.
var myFloors =
(from f in db.Floor
where f.BuildingId == txBuildingId
select new { f.FloorId }).ToArray();
Then, I am having trouble selecting based on that Array.
var model =
(from r in db.Room
where myFloors.Contains(r.FloorId)
select new
{
label = r.Name,
value = r.RoomId
});
I could do this easily in SQL with a string and by using the IN clause. I am fairly new to LINQ and am having alot of trouble with this. Any help would be much appreciated.
Upvotes: 1
Views: 89
Reputation: 75326
No need to have anonymous type in here, you can select floorId directly:
var myFloors =
(from f in db.Floor
where f.BuildingId == txBuildingId
select f.FloorId);
For more readable, I prefer using lambda style:
var myFloors = db.Floor.Where(f => f.BuildingId == txBuildingId)
.Select(f => f.FloorId);
So:
var model = db.Room.Where(r => myFloors.Contains(r.FloorId))
.Select(r => new {
label = r.Name,
value = r.RoomId
});
Upvotes: 3
Reputation: 54543
If you have Floor
reference defined in Room
, you can merge the 2 Linq queries to one, which is more efficient in terms of performance.
db.Room.Where(x=>x.Floor.BuildingId == txBuildingId).Select(r => new {
label = r.Name,
value = r.RoomId
})
Upvotes: 1