Reputation: 1485
I'm mapping a POCO into a model, code shown below.
// 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();
My problem is that in this line:
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(Src, 75)
Src
doesn't exist in the context.
Is there a way for me to declare a variable within the select that I can the reuse within the LINQ select?
And I don't want to call _storageService.GetFileUrl
twice.
Upvotes: 47
Views: 62218
Reputation: 11348
you can create a regular code block instead of running a single statement within the lambda expression, this way you can just declare a variable "src" and it will be available throughout the entire block - following regular scope rules.
noneRequiredUserDocuments = docs.Select(x => {
var src = _storageService.GetFileUrl(x.FileName);
return
new NoneRequiredUserDocument
{
StudentDocument = x,
Src = src,
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(Src, 75)
};
}).ToList();
Upvotes: 10
Reputation: 21795
You can declare a variable inside a Select
like this:-
noneRequiredUserDocuments = docs.Select(x =>
{
var src= _storageService.GetFileUrl(x.FileName);
return new NoneRequiredUserDocument
{
StudentDocument = x,
Src = src,
ThumbnailImageUrl = ImageHelper.ThumbnailImageUrl(src, 75);
};
}).ToList();
In query syntax
doing this is equivalent to:-
from x in docs
let src= _storageService.GetFileUrl(x.FileName)
select and so on..
Upvotes: 88
Reputation: 1038
You can use the "let" keyword:
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();
Upvotes: 16
Reputation: 16878
You can introduce temporary collection of anonymous type, with all necessary data:
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();
Upvotes: 3