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.
The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation.
While the LINQ methods always return a new collection, they don't create a new set of objects: Both the input collection (customers, in my example) and the output collection (validCustomers, in my previous example) are just sets of pointers to the same objects.
C# Language LINQ Queries Defining a variable inside a Linq query (let keyword)
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With