views:

234

answers:

1

Hello,

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 ?

+2  A: 

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?

  1. The code fetches all orders from the data store and stores them in a List<T>.

  2. The code creates a delegate of type Converter<TInput, TOutput> that converts from a single Order to a single OrderModel.

  3. The code converts all orders to order models by applying the converter to each order.

  4. 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?

dtb
it answers the question yes and no ;-) what the code is doing, but not why ;-)
msfanboy