使用ObservableCollection <t> </t> </t>包装IEnumerable <t>

时间:2010-11-25 21:16:27

标签: wpf mvvm viewmodel ienumerable

从我的存储库我总是IEnumerable<T>

在我的ViewModel的Ctor或方法中,我想将我的实体包装成ObservableCollection<T>,如下所示:

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); 

}

你会做什么?

2 个答案:

答案 0 :(得分:4)

假设您有从Customer到CustomerViewModel的某种转换:

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

答案 1 :(得分:3)

如何将Customer转换为CustomerViewModel?也许你只需要这样的东西:

customerViewModels = new ObservableCollection<CustomerViewModel>(
    from c in customers
    select new CustomerViewModel(c)
);