Search code examples
wpfmvvmviewmodelienumerable

Wrap an IEnumerable<T> with an ObservableCollection<T>


From my Repository I get always an IEnumerable<T>.

In the Ctor or a method of my ViewModel I want to wrap my entities into an ObservableCollection<T> like this:

private ObservableCollection<CustomerViewModel> customerViewModels;

public BillingViewModel(IService service)
{
   ...
   IEnumerable<Customer> customers = service.GetCustomers();

   // that will not work because of a different type
   customerViewModels = new ObservableCollection(customers); 

}

What would you do?


Solution

  • Assuming you have some sort of conversion from Customer to CustomerViewModel:

    customerViewModels = new ObservableCollection<CustomerViewModel>
        (customers.Select(c => ConvertToViewModel(c)));