sonia charan
sonia charan

Reputation: 17

extra condition inside ternary operator possible?

I have condition

        string columns = (protocol == null || protocol == 5) ? "Patient Id,Patient Initial,DOB,Age,Height,Weight,BMI,Occupation,Nationality,Education,Race,Gender,MaritalStatus," : "Patient Id,";

so its basically setting a string.

here i am checking just protocolt type and setting string as in the above code,

no i have some flags

  var age=false;
  var gender=false;

Normally if condition is true(protocl=5) the string contain age and gender;

i want to know in the same code i show above, i need to make some changes, i have two flags right?

if age==true; then only the string should contain age. if gender==false the string should not contain gender.

is it possible to put this condition check in the first one line code itself?

what is the best and less coded way to implement that?

Upvotes: 0

Views: 176

Answers (2)

Deepak Sharma
Deepak Sharma

Reputation: 419

Use

int? protocol = 5;
        bool age = true;
        var gender = true;
        string columns = "";
        if (protocol == 5)
        {
            columns += "Patient Id,";
        }

        if (age)
        {
            columns += "Age,";
        }

        if (gender)
        {
            columns += "Gender,";

        }
        columns += columns.TrimEnd(',');

add as many if as you want. Using ternary operator will make it complex.

Upvotes: 0

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20610

You might as well keep it simple and split it into two parts:

  1. Create a list of the columns you want
  2. Convert the list into a comma-separated string

Yes, it's longer and uses a bit more memory. But it's also easier to see what it's doing and to change the logic in future:

int? protocol = 5;
var age = false;
var gender = false;

var columnList = new List<string>();
columnList.Add("Patient Id");

if (protocol == null || protocol == 5)
{
    columnList.Add("Patient Initial");
    columnList.Add("DOB");

    if (age)
    {
        columnList.Add("Age");
    }

    columnList.Add("Height");
    columnList.Add("Weight");
    columnList.Add("BMI");
    columnList.Add("Occupation");
    columnList.Add("Nationality");
    columnList.Add("Education");
    columnList.Add("Race");

    if (gender)
    {
        columnList.Add("Gender");
    }

    columnList.Add("MaritalStatus");
}

string columns = string.Join(",", columnList);

Upvotes: 1

Related Questions