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.
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:
Or of course you could break it into a real method instead of a
Funcif you wanted to.If you’re able to, you may be better off doing something like:
Then you can do: