Creating a ternary condition in c#

Venkat :

I have the below datatable code in c# , which I want to make it as a ternary operator condition.

if (!string.IsNullOrEmpty(row[2].ToString()))
                            {
                                if (row[2].ToString().Length >= 3)
                                {
                                    row[2] = row[2].ToString().Substring(0, 3).ToUpper();
                                }
                                else
                                {
                                    row[2] = row[2].ToString().ToUpper();
                                }
                            }

How to achieve this ?

D Stanley :

How to achieve this ?

just copy your predicate, true expression, and false expression to the ternary form:

row[2] = {predicate} ? {true expression} : {false expression}

which gives:

if (!string.IsNullOrEmpty(row[2].ToString()))
{
    row[2] = row[2].ToString().Length >= 3 
           ? row[2].ToString().Substring(0, 3).ToUpper();
           : row[2].ToString().ToUpper();
}

you could simplify it a bit by factoring out the common expression:

if (!string.IsNullOrEmpty(row[2].ToString()))
{
    row2 = row[2].ToString().ToUpper();
    row[2] = row2.Length >= 3 
           ? row2.Substring(0, 3);
           : row2;
}

you could use a ternary operator for the last if and just set row[2] to itself if the condition doesn't match, but it's not a functional improvement and is harder to read IMHO.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398536&siteId=1