pdiddy
pdiddy

Reputation: 6297

Linq select different columns

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 ?

Upvotes: 2

Views: 1478

Answers (4)

Jarrett Widman
Jarrett Widman

Reputation: 6419

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

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 837946

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};

Upvotes: 1

Andrew Flanagan
Andrew Flanagan

Reputation: 4277

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.

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 190907

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

Upvotes: 1

Related Questions