tags:

views:

334

answers:

3

Something so simple, but my head is hurting over it, I'm sure I can write this in one line when converting, but how?

IQueryable<ion> ions =FindAllions();

List<ionFormViewModel> ionFormViewModels = new List<ionFormViewModel>();

foreach (ion ion in ions)
{
     ionFormViewModel ionFormViewModel = new ionFormViewModel(ion);
     ionFormViewModels.Add(ionFormViewModel);
}
+1  A: 

Try this:

List<ionFormViewModel> ionFormViewModels
    = ions.Select(i => new ionFormViewModel(i)).ToList();

The Enumerable.Select extension method allows you to project a new value into a new sequence for each value in your current sequence. Basically it gives you the ability to generate sequences from other sequences with a transformation step in between.

Then the Enumerable.ToList extension method simply creates a new List<T> from the Select method's resulting IEnumerable<T>.

Andrew Hare
A: 
ionFormViewModels = ions.Select(ion => new ionFormViewModel(ion)).ToList();
Philippe Leybaert
A: 
List<ionFormViewModel> ionFormViewModels = ions.Select(i => new ionFormViewModel(i)).ToList()
Arthur