缩短包含' null'序列的代码。测试

时间:2015-09-24 15:29:58

标签: c#

我能以某种方式将temp的两个作业连接到&语句中的一个条件(if)吗?

node temp = new node();
temp = queue.Find(match => match.Check_node_state(element.state));
if (temp == null)
    temp = explored_nodes.Find(match => match.Check_node_state(element.state));
if (temp == null)

4 个答案:

答案 0 :(得分:11)

您可以链接null coalescing operator

node temp = queue.Find(match => match.Check_node_state(element.state))
            ?? explored_nodes.Find(match => match.Check_node_state(element.state))
            ?? someOtherFind()
            ?? anotherFind();

if (temp == null)
    throw new Exception("This thing really does not exist!");

答案 1 :(得分:5)

在C#中,您想要的运算符是??,它允许您在第一个为空时提供备用值。声明看起来像这样:

node temp = queue.Find(match => match.Check_node_state(element.state))
  ?? explored_nodes.Find(match => match.Check_node_state(element.state));

答案 2 :(得分:1)

嗯,你当然可以这样做:

if (queue.Find(match => match.Check_node_state(element.state)) == null &&
    explored_nodes.Find(match => match.Check_node_state(element.state)) == null)

但我不认为它是巨大的改进......

请注意,您需要使用&&代替&来使代码等效,因为&&短路,而&将评估两者

答案 3 :(得分:1)

您可以使用if (!queue.Any(match => match.Check_node_state(element.state)) && !explored_nodes.Any(match => match.Check_node_state(element.state))) 使代码更具可读性:

INSERT ALL
  INTO PHMR_VIP (PHMR_VIP_ID,PHMR_VIP_NOM,PHMR_VIP_PRENOM) VALUES (SQ_PHMR_VIP.nextval, 'dfdf', 'dfdfd')
  INTO PHMR_VIP (PHMR_VIP_ID,PHMR_VIP_NOM,PHMR_VIP_PRENOM) VALUES (SQ_PHMR_VIP.nextval, 'ffdf', 'dfdf')
  INTO PHMR_VIP (PHMR_VIP_ID,PHMR_VIP_NOM,PHMR_VIP_PRENOM) VALUES (SQ_PHMR_VIP.nextval, 'mohfdfd','fdfdf')
SELECT * FROM dual;