Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use ternary operator in LINQ query

Tags:

c#

linq

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?

like image 926
Keith Adler Avatar asked Dec 17 '25 18:12

Keith Adler


1 Answers

d.SourceType is null.

You should call

(String.IsNullOrEmpty(d.SourceType) ? ", " + d.SourceType : string.Empty)
like image 64
SLaks Avatar answered Dec 20 '25 06:12

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!