Reputation: 6297
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
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
Reputation: 837946
What you are trying to do won't work because the two var
s 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
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
Reputation: 190907
Why don't you select the whole Model and use the fields when you need them?
Upvotes: 1