Création d'une condition ternaire c #

Venkat:

Je le ci-dessous le code datatable en c #, que je veux faire comme condition de l'opérateur ternaire.

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

Comment y parvenir?

D Stanley:

Comment y parvenir?

il suffit de copier votre prédicat, véritable expression et expression fausse à la forme ternaire:

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

qui donne:

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

vous pouvez simplifier un peu en affacturage sur l'expression commune:

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

vous pouvez utiliser un opérateur ternaire pour la dernière ifet vient de mettre row[2]à lui - même si la condition ne correspond pas, mais ce n'est pas une amélioration fonctionnelle et est plus difficile à lire à mon humble avis.

Je suppose que tu aimes

Origine http://10.200.1.11:23101/article/api/json?id=399827&siteId=1
conseillé
Classement