Cannot use ternary operator in LINQ query

I cannot understand why I am getting an error Object reference not set to an instance of an object.if I use the 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?

+3
source share
3 answers

d.SourceType null.

You have to call

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

You are checking a property Length SourceTypethat may be null.

+1
source

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

+1
source

Source: https://habr.com/ru/post/1748890/


All Articles