Coppermill
Coppermill

Reputation: 6794

IQueryable convert to list

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

Upvotes: 1

Views: 4574

Answers (3)

Andrew Hare
Andrew Hare

Reputation: 351516

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>.

Upvotes: 3

Arthur
Arthur

Reputation: 8129

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

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171774

ionFormViewModels = ions.Select(ion => new ionFormViewModel(ion)).ToList();

Upvotes: 0

Related Questions