Как использовать тернарный оператор для этого оператора в c#

Трассировщик лучей LINQ , конечно, превышает мой список =)

, я не совсем уверен, квалифицирует ли как изящный, но это - несомненно самое прохладное linq-выражение, которое я когда-либо видел!

, О, и только быть чрезвычайно ясным; я сделал не запись это (, Luke Hoban сделал)

11
задан MMalke 6 November 2019 в 16:52
поделиться

7 ответов

int five = 5;
string answer = five == 5 ? "true" : "false";

I see that you want to use this to write the values out in ASP.NET, the answer string will hold your desired value, use that as you please.

27
ответ дан 3 December 2019 в 01:13
поделиться

The ternary operator in just about every language works as an inline if statement:

Console.WriteLine((five == 5) ? 'true' : 'false');

(You shouldn't strictly need the inner parens, but I like to include them for clarity.)

If the boolean evaluates to true, then the entire expression is equal to the value between the ? and :. If the boolean evaluates to false, the expression equals the value after the :.

I don't believe you can include lines of code in the middle of the operator. These are simply supposed to be expressions that replace the entire operator "phrase" once the condition is evaluated.

I'm a Java guy and don't really know C#; maybe it's different. But probably not.

9
ответ дан 3 December 2019 в 01:13
поделиться

You could keep it really simple. Comparing five to 5 results in a boolean, so the following is also possible:

int five = 5;
Console.WriteLine((five == 5).ToString());

The bool type's ToString() method is already designed to return "True" or "False", and if the lowercase alternative is needed, thats simple too:

int five = 5;
Console.WriteLine((five == 5).ToString().ToLower());

If you don't need it lowercased, you can actually completely eliminate the ToString as well:

int five = 5;
Console.WriteLine(five == 5);
4
ответ дан 3 December 2019 в 01:13
поделиться

In ASP.NET, declarative (i.e, where the HTML goes):

<p>Is this five? <%= yourVariable == 5 ? "true" : "false"; %></p>

Or, alternatively, in code behind (i.e., where your C# code and classes are):

someTextBox.Text = yourVariable == 5 ? "true" : "false";
2
ответ дан 3 December 2019 в 01:13
поделиться
Response.Write(five == 5 ? "True" : "False");

Though, for this example, I wouldn't use the ternary operator at all:

Response.Write(five == 5);
1
ответ дан 3 December 2019 в 01:13
поделиться

На всякий случай вы должны поместить свои тернарные выражения в parens (), потому что тернарный оператор?: Имеет тонкий приоритет, который может вас укусить, если вы не смотрите.

string answer = ( (five==5) ? ("true") : ("false") );

Это вероятно, это не важно для этого примера, но если тернар является частью сложного выражения, правила приоритета могут заставить компилятор интерпретировать выражение иначе, чем вы предполагали.

1
ответ дан 3 December 2019 в 01:13
поделиться

five==5?console.writeline('true'):console.writeline('false')

It works like this:

<if-expression> ? <code-when-if-expression-evaluates-true> : <code-when-if-expression-evaluates-false>

EDIT:

What I had probably been thkinking:

<%=five==5?'true':'false'%>

0
ответ дан 3 December 2019 в 01:13
поделиться
Другие вопросы по тегам:

Похожие вопросы: