Reputation: 641
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...
Upvotes: 1
Views: 1111
Reputation: 41213
Use the null coalescing operator:
Phone = person.Element("PHONE") ?? String.Empty;
Upvotes: 0
Reputation: 1500095
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()
};
Upvotes: 2