三元运算符内的额外条件可能吗?
string columns = (protocol == null || protocol == 5) ? "Patient Id,Patient Initial,DOB,Age,Height,Weight,BMI,Occupation,Nationality,Education,Race,Gender,MaritalStatus," : "Patient Id,";
所以它基本上设置一个字符串。
这里我检查只是protocolt类型和设置字符串,如上面的代码,
人无我有一些标志
var age=false;
var gender=false;
一般来说,如果条件为真(通讯协定= 5)字符串包含年龄和性别;
我想知道在上面显示的相同代码中,我需要进行一些更改,我有两个标记对吗?
if age == true;那么只有字符串应该包含年龄。 如果gender == false,则该字符串不应包含性别。
是否有可能把这种情况检查在第一个行代码本身?
什么是最好的和较少编码的方式来实现呢?
你还不如保持简单,它分成两个部分:
- 创建要
- 转换列表到逗号分隔的字符串
列的列表是的,它更长,并使用更多的内存。但它也更容易看到它在做什么,并在将来改变逻辑:
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);
使用
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(',');
添加如果你想要的。使用三元运算符会使其变得复杂。
?认为我有字符串中的每个项目的标志,如果相应的标志是真的,它应该显示,否则它不应该显示该标志。所以对于每个项目我必须检查condition.like dob,年龄,身高,..等都有各自的标志。 –
http://rextester.com/FLD80835它不起作用 –
它的返回时间因为布尔年龄=真。你想以其他方式管理吗? –
_“什么是最好的和更少编码的方式来实现呢?”_最好的方式不一定总是编写代码尽可能短,并尝试将其全部放在一行中。编写易于理解和维护的代码。 –
不要忘记 - 容易*其他*了解和维护:) – Charleh
逻辑不是很清楚。你的条件操作符只是检查协议是否为空或5,然后返回所有的字段(不仅如上所述的年龄和性别),否则它返回''患者ID'“。那有意义吗?你能解释一下吗? –