tags:

views:

109

answers:

4

I'd like select different column based on some variable

instead of doing something like this

if(selectLastName)
   var res = from e in ctx.Employees
             select new {e.FirstName, e.LastName};
else
   var res = from e in ctx.Employees
             select new {e.FirstName}

How can I re-write this ?

+1  A: 

Why don't you select the whole Model and use the fields when you need them?

Daniel A. White
I'd have to agree, because trying to decide what to do with that `var res` after that if/else block ends will be very difficult.
echo
its just that the field i'm selecting is an xml field. So sometimes i don't want to bring it back
pdiddy
+1  A: 

What you are trying to do won't work because the two vars have different types. Try something like this instead:

 var res = from e in ctx.Employees
           select new {e.FirstName, selectLastName ? e.LastName : null};
Mark Byers
already try this and it doesn't work
pdiddy
A: 

column based on some variable

You can use the Dynamic LINQ library to do this sort of things if you need more flexibility. So instead of writing out strongly typed LINQ statements, you can construct them on the fly.

Some info here. There's a lot resources out there including some Stack Overflow questions like this one.

Andrew Flanagan
+1  A: 

This is just a modification of Mark's answer where there will always be a last name in the type but you won't always pull the value back from the db. I would have wrote it as a comment on his answer but there is no code formatting in the comments.

ctx.Employees.Select(e => new {
FirstName = e.FirstName,
LastName = selectLastName ? e.LastName : null
});
jarrett
Adding LastName = xxxx worked. Thanks!
pdiddy