我正在将POCO映射到模型中,代码如下所示。
// NOT NEEDED var noneRequiredUserDocuments = new List<NoneRequiredUserDocument>();
//var docs = studentDocuments.Where(x => x.RequiredUserDocumentId == null); // NOT NEEDED .ToList();
//var noneRequiredUserDocuments = docs.Select(x => new NoneRequiredUserDocument
// You can chain LINQ methods (i.e. Where and Select)
var noneRequiredUserDocuments = studentDocuments
.Where(x => x.RequiredUserDocumentId == null)
.Select(x => new NoneRequiredUserDocument
{
StudentDocument = x,
Src = _storageService.GetFileUrl(x.FileName),
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(Src, 75)
}).ToList();
我的问题在于这一行:
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(Src, 75)
Src
在上下文中不存在。
我有没有办法在select中声明一个我可以在LINQ select中重用的变量?
我不想两次致电_storageService.GetFileUrl
。
答案 0 :(得分:38)
您可以在Select
内声明一个变量,如下所示: -
noneRequiredUserDocuments = docs.Select(x =>
{
var src= _storageService.GetFileUrl(x.FileName);
return new NoneRequiredUserDocument
{
StudentDocument = x,
Src = src,
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(src, 75);
};
}).ToList();
在query syntax
这样做相当于: -
from x in docs
let src= _storageService.GetFileUrl(x.FileName)
select and so on..
答案 1 :(得分:8)
您可以使用“let”关键字:
var list = (from x in docs
let temp = _storageService.GetFileUrl(x.FileName)
select new NoneRequiredUserDocument
{
StudentDocument = x,
Src = temp,
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(temp, 75)
}).ToList();
答案 2 :(得分:6)
你可以创建一个常规代码块,而不是在lambda表达式中运行单个语句,这样你就可以声明一个变量&#34; src&#34;并且它将在整个块中可用 - 遵循常规范围规则。
noneRequiredUserDocuments = docs.Select(x => {
var src = _storageService.GetFileUrl(x.FileName);
return
new NoneRequiredUserDocument
{
StudentDocument = x,
Src = src,
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(Src, 75)
};
}).ToList();
答案 3 :(得分:2)
您可以使用所有必要的数据引入匿名类型的临时集合:
noneRequiredUserDocuments = docs
.Select(x => new { Data = x, Src = _storageService.GetFileUrl(x.FileName) }
.Select(x => new NoneRequiredUserDocument
{
StudentDocument = x.Data,
Src = x.Src
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(x.Src, 75)
}).ToList();