from some code I found in Sacha Barbers free mvvm framework chinch I saw this:
return new DispatcherNotifiedObservableCollection<OrderModel>(
DataAccess.DataService.FetchAllOrders(
CurrentCustomer.CustomerId.DataValue).ConvertAll(
new Converter<Order, OrderModel>(
OrderModel.OrderToOrderModel)));
FetchAllOrders
returns a List<Order>
for a certain customerID.
This list is converted to a List<OrderModel>
or in other words List<OrderViewModel>
.
How can that happen? What must be the requirements/conditions, that every property of the Order object in the List<Order>
is converted into a property of the OrderModel
?
Let's make that code a bit more readable:
List<Order> orders =
DataAccess.DataService.FetchAllOrders(CurrentCustomer.CustomerId.DataValue);
Converter<Order, OrderModel> converter =
new Converter<Order, OrderModel>(OrderModel.OrderToOrderModel);
List<OrderModel> orderModels = orders.ConvertAll(converter);
return new DispatcherNotifiedObservableCollection<OrderModel>(orderModels);
What happens here?
The code fetches all orders from the data store and stores them in a List<T>.
The code creates a delegate of type Converter<TInput, TOutput> that converts from a single Order to a single OrderModel.
The code converts all orders to order models by applying the converter to each order.
The code returns a DispatcherNotifiedObservableCollection<T> with the list of converted values.
How does it work?
Basically, what ConvertAll does here, is equivalent to this:
List<OrderModel> orderModels = new List<OrderModel>(orders.Count);
for (int i = 0; i < orders.Count; i++)
{
orderModels[i] = OrderModel.OrderToOrderModel(orders[i]);
}
Does that answer your question?