1

I have a ViewComponent, and DTO and ViewModel classes. I want to pass a list of ViewModels to the view, but because of async/await I cannot do it in one line like so:

 List<PageVM> pages = await _context.Pages.ToArray().Where(x => x.Slug != "home").OrderBy(x => x.Sorting).Select(x => new PageVM(x)).ToList();

I can do it in more lines like so:

List<PageVM> pages = new List<PageVM>();

List<PageDTO> dto = await _context.Pages.Where(x => x.Slug != "home").ToListAsync();

foreach (var item in dto)
{
    pages.Add(new PageVM(item));
}

But is it possible to modify the one line so it works with await?

2 Answers 2

2

Yes, it is; note the parentheses:

var pages = (await _context.Pages.Where(x => x.Slug != "home").ToListAsync()).Select(x => new PageVM(x)).ToList();

However, this is equivalent to the following two statements:

var dtos = await _context.Pages.Where(x => x.Slug != "home").ToListAsync();
var pages = dtos.Select(x => new PageVM(x)).ToList();

which IMO is much easier to read.

Sign up to request clarification or add additional context in comments.

Comments

0

Yes, you need to wrap the awaited expression with parenthesis. Something like this should do.

List<PageVM> pages = (await _context.Pages.Where(x => x.Slug != "home").ToListAsync())
.Select(item => new PageVM(item)).ToList();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.