Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq select returning string instead of object

Tags:

c#

lambda

linq

I have the following code:

var languages = _languageService
            .GetAll()
            .Select(x => (((LanguageViewModel) new LanguageViewModel().InjectFrom(x))))
            .ToList();

When executing this, languages becomes, as expected, a collection of LanguageViewModel objects:

Working

What I am trying to do is, when selecting, also convert the object's Code property to uppercase, as so:

var languages = _languageService
            .GetAll()
            .Select(x => (((LanguageViewModel) new LanguageViewModel().InjectFrom(x)).Code = x.Code.ToUpper()))
            .ToList();

I'm expecting the languages object to have multiple LanguageViewModels in it but it looks like this:

enter image description here

My guess is the fact that I'm using a statement like Select(x => (new Object().Property = Value)) it selects the Property. But then, how can I return an object with one of its properties changed? Using object initializer before inject is not an option as it gets overriden, using it after the Inject is not possible, as it is not casted yet, so I got to the solution here which does not seem to work. Any advice greatly appreciated.

like image 950
iuliu.net Avatar asked Jan 07 '16 15:01

iuliu.net


2 Answers

You can't write the lambda body as a single expression that does what you want, but you don't need to. You can put multiple statements in a lambda:

var languages = _languageService
    .GetAll()
    .Select(x => {
        var lvm = (LanguageViewModel)new LanguageViewModel().InjectFrom(x);
        lvm.Code = x.Code.ToUpper();
        return lvm;
    })
    .ToList();
like image 142
15ee8f99-57ff-4f92-890c-b56153 Avatar answered Sep 29 '22 11:09

15ee8f99-57ff-4f92-890c-b56153


Your Select line could be rewritten to

.Select(x =>
 {
  var vm = new LanguageViewModel().InjectFrom(x);
  vm.Code = vm.Code.ToUpper();
  return vm;
 })
like image 31
Jamiec Avatar answered Sep 29 '22 13:09

Jamiec