2010-06-07 78 views
3

我找不到为什么我在我的LINQ查询中使用三元运算符时出现Object reference not set to an instance of an object.错误。不能在LINQ查询中使用三元运算符

var courses = from d in somesource 
          orderby d.SourceName, d.SourceType 
          select new 
          { 
           ID = d.InternalCode, 
           Name = string.Format("{0} - {1}{2}", d.InternalCode, d.SourceName, (d.SourceType.Length > 0 ? ", " + d.SourceType : string.Empty)) 
          }; 

有什么想法?

回答

8

d.SourceTypenull

你应该叫

(String.IsNullOrEmpty(d.SourceType) ? ", " + d.SourceType : string.Empty) 
+0

你是对的。事实证明,即使它是一个字符串,如果它为空,它也会返回null。谢谢。一旦它允许我,我会选择你作为正确的答案。我已经提出了类似的答案。 – 2010-06-07 17:14:57

1

你检查SourceTypeLength属性,它可能为空。

1

也许SourceType为null,所以你会在d.SourceType.Length上得到异常。