Reputation: 109
I am new to LINQ, i need to write a LINQ statement with CASE statement. I am trying to convert the following query to linq. Here 1 and 0 are boolean. How can i achive this
Select CASE [db].[table] WHEN 1 THEN 'Yes' WHEN 0 THEN 'No' END AS Options from table
I tried the following but now working
Options = table.Options = 1 ? "Yes" : table.Options = 0 ? "No"
Upvotes: 3
Views: 5168
Reputation: 63752
There's a few things you've done wrong - one, the syntax of the ternary operator is
condition ? resultIfTrue : resultIfFalse
Second, you need to use the equality operator (==
) for comparison, not the assignment (=
) operator.
Thus, table.Options = 1 ? "Yes" : table.Options = 0 ? "No"
should be replaced with
table.Options == 1 ? "Yes" : "No"
Depending on your actual LINQ provider, there might be a helper to allow you to build SQL-like case
expressions (both the conditional and the choice-y type), but that's impossible to say without knowing exactly what you're using. If there is no helper, you'll have to do with the ternary operator (which is a bit crazy to read for more than a single condition, but oh well...).
For example, my LINQ provider uses the following syntax:
Case(table.Options).When(1, "Yes").Else("No").End()
or
Case().When(table.Options == 1, "Yes").Else("No").End()
But again, the only standard way is the ternary operator. Have a look in the documentation of your particular LINQ provider to see if it supports the SQL-like case
expressions and how.
Upvotes: 4
Reputation: 493
You need to address the table: I would try:
Options = db.table.ToList().Select(X => X.Options == 1 ? "Yes" : "No";
Upvotes: 1