Patrick
Patrick

Reputation: 146

Null Linq Values

I cant get this to work. The State field is empty on certain occassions, I am trying to get the result to return "--" if it is empty, or doesn't exist.

var CusipFields = from c in xml.Descendants("LISTARRAY")
                                  orderby c.Element("ASKYIELD").Value descending
                                  select new BondData()
                                  {

                                      CUSIP = c.Element("CUSIP").Value,
                                      Description = (string)c.Element("ISSUER").Value,
                                      Maturity= c.Element("MATURITYDT").Value,
                                      AskYield = float.Parse(c.Element("ASKYIELD").Value),
                                      State = (string)c.Element("STATE").Value ?? "--"
                                  }
                                  ;

This just doesn't want to work. The error I am getting is:

NullReferenceException was unhandled. {"Object reference not set to an instance of an object."}

I KNOW that it does not exist. I thought that putting ?? "--" will return "--" if c.Element("STATE").Value is null.

I can resort to modifying the statement to:

var CusipFields = from c in xml.Descendants("LISTARRAY")
                                  orderby c.Element("ASKYIELD").Value descending
                                  select c;
foreach(var t in CusipFields)
{
   switch(t.name)
    {
    }
}

But I think that it is slower. And its not what I want.

Upvotes: 0

Views: 178

Answers (3)

anthonyvd
anthonyvd

Reputation: 7590

I think it's because c.Element("STATE") is null, not it's Value property.

try:

(string)c.Element("STATE") != null? (string)c.Element("STATE").Value : "--";

Upvotes: 1

Brian Driscoll
Brian Driscoll

Reputation: 19635

You're getting this error not because the Value property is null, but because c.Element(...) is null. You'll need to check for nulls in all of your Element() calls and take appropriate action in order to avoid this error.

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

Use this:

State = (string)c.Element("STATE") ?? "--"

instead of

 State = (string)c.Element("STATE").Value ?? "--"

My answer assumes, that your problem is, that the STATE element is missing, not empty. Please tell me, whether or not that fixed your problem.

Upvotes: 4

Related Questions