简体   繁体   English

在Linq中与Select()异步等待

[英]async await with Select() in Linq

I have a ViewComponent , and DTO and ViewModel classes. 我有一个ViewComponent ,以及DTOViewModel类。 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: 我想将ViewModels的列表传递给视图,但是由于async/await我无法像这样在一行中完成它:

 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 ? 但是是否可以修改一行以使其与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. 哪个IMO更容易阅读。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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