views:

102

answers:

3

Dear All,

SELECT * FROM CUSTOMERS WHERE RTRIM(ISNULL([SHORTNAME],'')) LIKE '%john%'

I want to write this using Linq,

var persons = from person in xmlDoc.Descendants("Table")
where 
person.Element("SHORTNAME").Value.Contains("123")
select new
{
  shortName = person.Element("SHORTNAME").Value,
  longName = person.Element("LONGNAME").Value,
  address = person.Element("ADDRESS").Value,
  Phone = person.Element("PHONE") != null ? person.Element("PHONE").Value : "",
  zip = person.Element("ZIPCODE") != null ? person.Element("ZIPCODE").Value : "",
};

This works fine when [SHORTNAME] is not null, if [SHORTNAME] is a null value this breakes the code and pops up a "Null Reference Exception"

Please help me...

+2  A: 

Assuming you're trying to avoid picking up anything where there isn't a short name...

var persons = from person in xmlDoc.Descendants("Table")
    let shortNameElement = person.Element("SHORTNAME") 
    where shortNameElement != null && shortNameElement.Value.Contains("123")
    select new
    {
        shortName = person.Element("SHORTNAME").Value,
        longName = person.Element("LONGNAME").Value,
        address = person.Element("ADDRESS").Value,
        Phone = person.Element("PHONE") != null ? 
            person.Element("PHONE").Value : "",
        zip = person.Element("ZIPCODE") != null ? 
            person.Element("ZIPCODE").Value : "",
    };

Alternatively, you can use the null coalescing operator to make all of these a bit simpler:

var emptyElement = new XElement("ignored", "");

var persons = from person in xmlDoc.Descendants("Table")
    where (person.Element("SHORTNAME") ?? emptyElement).Value.Contains("123")
    select new
    {
        shortName = person.Element("SHORTNAME").Value,
        longName = person.Element("LONGNAME").Value,
        address = person.Element("ADDRESS").Value,
        Phone = (person.Element("PHONE") ?? emptyElement).Value
        zip = (person.Element("ZIPCODE") ?? emptyElement).Value
    };

Or alternatively, you could write an extension method:

public static string ValueOrEmpty(this XElement element)
{
    return element == null ? "" : element.Value;
}

and then use it like this:

var persons = from person in xmlDoc.Descendants("Table")
    where person.Element("SHORTNAME").ValueOrEmpty().Contains("123")
    select new
    {
        shortName = person.Element("SHORTNAME").Value,
        longName = person.Element("LONGNAME").Value,
        address = person.Element("ADDRESS").Value,
        Phone = person.Element("PHONE").ValueOrEmpty(),
        zip = person.Element("ZIPCODE").ValueOrEmpty()
    };
Jon Skeet
A: 

Use the null coalescing operator:

Phone = person.Element("PHONE") ?? String.Empty;
Julien Lebosquain
That won't work, as Element returns an XElement, not a string.
Jon Skeet
My bad, seemed to simple at the moment I wrote it.
Julien Lebosquain