开发者

Cannot use ternary operator in LINQ query

开发者 https://www.devze.com 2023-01-02 19:42 出处:网络
I can\'t figure out why I get a Object reference not set to an instance of an object. error if I use a ternary operator in my LINQ query.

I can't figure out why I get a Object reference not set to an instance of an object. error if I use a ternary operator in my LINQ query.

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))
                          };

Any thoughts?


d.SourceType is null.

You should call

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


You're checking the Length property of SourceType, which could be null.


Maybe SourceType is null, so you get exception on d.SourceType.Length.

0

精彩评论

暂无评论...
验证码 换一张
取 消