内联if语句不起作用
问题描述:
由于某些原因,当我将三进制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
};
如果在该位置声明,你可以没有三元?
答
有一个问题,是entity.Phone null?如果是这样,那将是原因。
附注:我不得不说,这是储存电话号码的一种奇怪的方式..
UPDATE
的问题是与“entity.Phone.Length”的一部分。如果电话为空,那么你不能访问它的长度属性...因此错误。所以你需要添加一个空测试。喜欢的东西:
Phone = ((entity.Phone != null) && (entity.Phone.Length < 5)) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(entity.Phone)) : entity.Phone
这样一来,如果是空你只是发射空值。
答
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
};
这可能会解决您的问题。
什么是“一元”if语句? –
@Peter:一个例子是* i ++; * OP显然没有问题。我认为我们的好医生一直在寻找的是Ternary。 http://en.wikipedia.org/wiki/Ternary_operation纠正。 – NotMe
'? :'被称为*条件运算符。*(它实际上是三元的,不是一元的)。http://msdn.microsoft.com/en-us/library/ty67wk28.aspx –