This is a follow up question to the one answered here: Excluding dates from Linq Query in MVC .net application – which I’m very grateful for.
I’m hoping that someone can check my syntax in my Linq query below – to confirm if it’s the best way to build the query up, or if my use of the syntax is inefficient.
public class Room
{
public int RoomId { get; set; }
[Display(Name = "Room Name")]
public string Name { get; set; }
public bool Disabled { get; set; }
public virtual ICollection<Client> Clients { get; set; }
}
public class Client
{
public int ClientId { get; set; }
public int RoomId { get; set; }
public string ClientName { get; set; }
public DateTime Arrival { get; set; }
public DateTime Departure { get; set; }
public virtual Room Room { get; set; }
}
Clients lists a row for each client who has a particuar room booked. I have 3 rooms, Room 1, Room 2, and Room 3. So entries in the client table could be:
Client 1, Room 1, Mr Smith, Arr: 2012-07-08, Dep: 2012-07-10
Client 2, Room 1, Mr Jones, Arr: 2012-07-14, Dep: 2012-07-20
Client 3, Room 2, Mr Alas, Arr: 2012-07-12, Dep: 2012-07-15
Given an arrival and departure date, I’m trying to take my whole list of rooms, and take away any that have a client staying where the arrival or departure dates overlap. So using the data above, if I had an arrival date of 2012-07-12 and a departure date of 2012-07-13, then Room 2 would not be available, however, Room 1, does not have any bookings spanning that date – so Room 1 I want to leave in my result set.
So my Linq query (I’m new to Linq, so please point out where I may be going wrong) is:
var dteFrom = DateTime.Parse("2012-07-12");
var dteTo = DateTime.Parse("2012-07-13");
var rooms = (from r in Rooms
where !r.Clients.Any(
client =>
( dteFrom >= client.Arrival && dteFrom <= client.Departure )
||
( dteTo >= client.Arrival && dteFrom <= client.Departure )
||
( dteFrom <= client.Arrival && dteTo >= client.Departure )
)
select r);
Given that I’m looking to include ALL rooms, EXCEPT any that meet the criteria, can anyone confirm that my use of .Any and ! and || are correct, as far as LINQ goes?
Is there any better way within the syntax, of excluding records from the Rooms list?
Thank you again for any help,
Mark
Looks fine to me – one thing that may help readability would be to compose your query in two steps:
Remembering that the query is only executed, when the results are enumerated – so there’s no performance cost to doing this in two steps.