2011-09-28 117 views
0

由于某些原因,当我将三进制if语句添加到此位代码时,会引发NullPointerException。我不太清楚为什么...有什么想法?这是jqGrid的方法 - 返回Json数据。内联if语句不起作用

var gridModel = from entity in vendorList.AsQueryable() 
      select new 
      { 
       VendorId = "<a href='/Admin/DetailsPlan/" + entity.VendorId + "'><img src='/Images/next_icon_sm.png' class='icon' alt='View Vendor' /></a>", 
       VendorNm = entity.VendorNm, 
       Phone = (entity.Phone.Length < 5) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(entity.Phone)) : entity.Phone, 
       City = entity.City, 
       State = entity.LkState.StateAbbr 
      }; 

如果在该位置声明,你可以没有三元?

+0

什么是“一元”if语句? –

+1

@Peter:一个例子是* i ++; * OP显然没有问题。我认为我们的好医生一直在寻找的是Ternary。 http://en.wikipedia.org/wiki/Ternary_operation纠正。 – NotMe

+1

'? :'被称为*条件运算符。*(它实际上是三元的,不是一元的)。http://msdn.microsoft.com/en-us/library/ty67wk28.aspx –

回答

1

有一个问题,是entity.Phone null?如果是这样,那将是原因。

附注:我不得不说,这是储存电话号码的一种奇怪的方式..

UPDATE

的问题是与“entity.Phone.Length”的一部分。如果电话为空,那么你不能访问它的长度属性...因此错误。所以你需要添加一个空测试。喜欢的东西:

Phone = ((entity.Phone != null) && (entity.Phone.Length < 5)) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(entity.Phone)) : entity.Phone 

这样一来,如果是空你只是发射空值。

+0

在某些情况下,它为空。然而,如果我有任何String.Format(实体....)或者如果我只是显示手机...没有错误..但两者的组合使它不出现。 – Cody

+0

Ahhhhhhhhhh ....这是有道理的。 DERP。让我改变这个... – Cody

+0

完美。就是这样,谢谢。 – Cody

2
var gridModel = from entity in vendorList.AsQueryable() 
    let unformattedPhone = entity.Phone??string.Empty 
    select new 
    { 
     VendorId = "<a href='/Admin/DetailsPlan/" + entity.VendorId + "'><img src='/Images/next_icon_sm.png' class='icon' alt='View Vendor' /></a>", 
     VendorNm = entity.VendorNm, 
     Phone = (unformattedPhone.Length < 5) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(unformattedPhone)) : unformattedPhone, 
     City = entity.City, 
     State = entity.LkState.StateAbbr 
    }; 

这可能会解决您的问题。

+0

分号是错字吗? – Cody

+0

是oops:P我做了更正 –

+0

它最终成为'entity.phone.Length <5' - 在某些情况下,entity.phone为空。然而,你的解决方案看起来很有趣 - 行'let unformattedPhone = entity.Phone ?? string.empty' double?手段? – Cody