Samuel
Samuel

Reputation: 12341

Convert lambda expression to linq query

Is there any way to convert this lambda expression in linq query?

function List<ViewModel> CreateViewModels(List<Model> models)
{
   return models.Select(x =>
   {
      var viewModel = new ViewModel();

      this.UpdateViewModel(x, viewModel);

      return viewModel;
   }).ToList();
}

Where 'UpdateViewModel' is a function that transfer the values from the Model object to the ViewModel object.

Ok, this code is clean but I'm wondering to know if there is the equivalent with a linq query.

Upvotes: 2

Views: 2195

Answers (1)

Joe Enos
Joe Enos

Reputation: 40383

I'd agree that you've probably got it right - the method-chaining syntax is pretty useful, and is actually my preferred method for writing LINQ.

But if you really want to use the LINQ query syntax, I think you'd have to do something like this, which basically just breaks out the big lambda into something separate:

Func<Model, ViewModel> func = m =>
    {
        var viewModel = new ViewModel();
        this.UpdateViewModel(m, viewModel);
        return viewModel;
    };

return (from m in models
        select func(m)
       ).ToList();

Or of course you could break it into a real method instead of a Func if you wanted to.

If you're able to, you may be better off doing something like:

public class ViewModel
{
    public ViewModel(Model m)
    {
        // Do whatever it is you're currently doing in UpdateViewModel
    }
}

Then you can do:

from m in models
select new ViewModel(m)

Upvotes: 4

Related Questions