Declare variable within LINQ select(x => new

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..

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

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

Tags:

C#

Linq