2010-06-07 77 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上得到異常。