简体   繁体   中英

async await with Select() in Linq

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 ?

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.

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

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