So you have to tables Customers
and Orders
, and there is a one-to-many relation between Customers and Orders: Every Customer has zero or more Orders, every Order belongs to exactly one Customer, namely the Customer that the foreign key CustomerId
refers to.
Every Customer has a property Time. (Are you sure Time is a Customer property, not a property of an Order?). You have two DateTime values: timeStart and timeEnd, and from every Customer that has a value for property time between timeStart and timeEnd, you want one of his Orders, doesn't matter which one, or null if this Customer doesn't have any Orders.
In baby steps:
DateTime timeStart = ... // = '2021-01-01 10:00:00'
DateTime timeEnd = ... // = '2021-01-01 11:00:00'
IQueryable<Order> allOrders = ...
IQueryable<Customer> allCUstomers = ...
IQueryable<Customer> customersWithinTimeRanges = allCustomers
.Where(customer => timeStart <= customer.Time and customer.Time < timeEnd);
In words: from all Customers, keep only those Customers that have a value of property Time that is between timeStart and timeEnd (using propery <= and <)
Now from every Customer within time range, you want one of his Orders, or null if the Customer doesn't have any Order.
Whenever you have a one-to-many relation, like Schools with their zero or more Students, Cities with their zero or more inhabitants, or in your case: Customers with their zero or more Orders, and from every "one" you want zero or more of his "many" items, consider to use one of the overloads of Queryable.GroupJoin
I almost always need the overload with a parameter resultSelector
var customersWithAnOrder = customersWithinTimeRanges.GroupJoin(
allOrders,
customer => customer.Id, // from every Customer take the primary key
order => order.CustomerId, // from every Order take the foreign key
// parameter resultSelector: from every Customer with his zero or more Orders
// make one new object:
(customer, ordersOfThisCustomer) => new
{
// select the Customer properties that you plan to use:
Id = customer.Id,
Name = customer.Name,
...
Order = ordersOfThisCustomer.Select(order => new
{
// select the Order properties that you plan to use
Id = order.Id,
Date = order.Date,
...
// not needed, you already got the value in property Id:
// CustomerId = order.CustomerId
})
// you don't need all Orders of this Customer, you only want one,
// don't care which one or null if this Customer doesn't have any Orders
.FirstOrDefault(),
});
Sometimes the database doesn't allow you to do FirstOrDefault
if you haven't sorted the sequence. In that case, sort before FirstOrDefault:
Order = ordersOfOfThisCustomer.Select(order => new {...})
.OrderBy(order => order.Date) // or whatever you want to sort on
.FirstOrDefault(),