2016-09-28 51 views
0

我條件三元運算符內的額外條件可能嗎?

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

所以它基本上設置一個字符串。

這裏我檢查只是pr​​otocolt類型和設置字符串,如上面的代碼,

人無我有一些標誌

var age=false; 
    var gender=false; 

一般來說,如果條件爲真(通訊協定= 5)字符串包含年齡和性別;

我想知道在上面顯示的相同代碼中,我需要進行一些更改,我有兩個標記對嗎?

if age == true;那麼只有字符串應該包含年齡。 如果gender == false,則該字符串不應包含性別。

是否有可能把這種情況檢查在第一個行代碼本身?

什麼是最好的和較少編碼的方式來實現呢?

+9

_「什麼是最好的和更少編碼的方式來實現呢?」_最好的方式不一定總是編寫代碼儘可能短,並嘗試將其全部放在一行中。編寫易於理解和維護的代碼。 –

+1

不要忘記 - 容易*其他*瞭解和維護:) – Charleh

+0

邏輯不是很清楚。你的條件操作符只是檢查協議是否爲空或5,然後返回所有的字段(不僅如上所述的年齡和性別),否則它返回''患者ID'「。那有意義嗎?你能解釋一下嗎? –

回答

1

你還不如保持簡單,它分成兩個部分:

  1. 創建要
  2. 轉換列表到逗號分隔的字符串

列的列表是的,它更長,並使用更多的內存。但它也更容易看到它在做什麼,並在將來改變邏輯:

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); 
0

使用

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(','); 

添加如果你想要的。使用三元運算符會使其變得複雜。

+0

?認爲我有字符串中的每個項目的標誌,如果相應的標誌是真的,它應該顯示,否則它不應該顯示該標誌。所以對於每個項目我必須檢查condition.like dob,年齡,身高,..等都有各自的標誌。 –

+0

http://rextester.com/FLD80835它不起作用 –

+0

它的返回時間因爲布爾年齡=真。你想以其他方式管理嗎? –