简体   繁体   中英

Converting IEnumerable<X> to IEnumerable<Y>

IEnumerable<ContactPerson> results = _contactPersonRepository.GetContactPersons().Where(x => x.UserId == user.UserId);
IEnumerable<ContactPersonViewModel> contactPersons = results...

How can I do this? I have IEnumerable<X> and then I want to convert it in IEnumerable<Y> .

Is there any way to do this?

Regards

Use Select (if you want project Y to new type X) or Cast (if Y is inherited from X) extensions of IEnumerable<T> :

IEnumerable<ContactPersonViewModel> contactPersons = 
    results.Select(p => CreateContactPersonViewModelFrom(p));

If ContactPersonViewModel is ContactPerson:

IEnumerable<ContactPersonViewModel> contactPersons = 
    results.Cast<ContactPersonViewModel>();

Usually creating view model involves manual properties mapping from entity to view model. Like this:

IEnumerable<ContactPersonViewModel> contactPersons = 
    results.Select(p => new ContactPersonViewModel {
                       Name = p.Name,
                       Phone = p.Phone
                   });

So I also suggest you to take look on some mapping framework like Automapper . It makes lot of mappings for you. And this code will look like:

IEnumerable<ContactPersonViewModel> contactPersons = 
    Mapper.Map<IEnumerable<ContactPersonViewModel>>(results);

Sure, Enumerable.Select :

var contactPersons = results.Select(r => new ContactPersonViewModel(r));

This assumes there's a ContactPersonViewModel constructor that takes a ContactPerson ; if not, you will have to supply another way to initialize the viewmodel.

Try to cast it.

 IEnumerable<ContactPerson> results = _contactPersonRepository.GetContactPersons().Where(x => x.UserId == user.UserId);

 IEnumerable<ContactPersonViewModel> contactPersons = results.Cast<ContactPersonViewModel>();

One way of doing it would be Select method:

IEnumerable<ContactPersonViewModel> contactPersons = results.Select(x => new ContactPersonViewModel 
{
   Id = x.Id
   //...
});

This may helps (you can use the Select method):

  IEnumerable<ContactPersonViewModel> contactPersons = 
      results.Select(i=>new ContactPersonViewModel(){/*set your parameters */});

Don't forget to add the using System.Linq;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM