Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare variable within LINQ select(x => new

Tags:

c#

linq

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.

like image 260
Michael Esteves Avatar asked Mar 25 '15 08:03

Michael Esteves


People also ask

What does => mean in LINQ?

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.

Does LINQ select return new object?

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.

What keyword would you use to define an inline variable in a Linq query?

C# Language LINQ Queries Defining a variable inside a Linq query (let keyword)

What is any () in LINQ?

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.


Video Answer


1 Answers

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.. 
like image 97
Rahul Singh Avatar answered Sep 29 '22 17:09

Rahul Singh