包装一个IEnumerable 使用ObservableCollection

问题描述 投票:0回答:2

从我的存储库我总是得到一个IEnumerable<T>

在Ctor或我的ViewModel的方法中,我想将我的实体包装成像这样的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); 

}

你会怎么做?

wpf mvvm viewmodel ienumerable
2个回答
4
投票

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

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

3
投票

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

customerViewModels = new ObservableCollection<CustomerViewModel>(
    from c in customers
    select new CustomerViewModel(c)
);
© www.soinside.com 2019 - 2024. All rights reserved.