LINQ to XML中的ISNULL()

时间:2009-10-05 11:23:05

标签: c# linq linq-to-xml

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

我想用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 : "",
};

当[SHORTNAME]不为空时,如果[SHORTNAME]为空值,这会破坏代码并弹出“空引用异常”

请帮帮我......

2 个答案:

答案 0 :(得分:2)

假设你试图避免拾取不是短名称的任何内容......

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 : "",
    };

或者,您可以使用null coalescing运算符使所有这些更简单:

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
    };

或者,您可以编写扩展方法:

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

然后像这样使用它:

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()
    };

答案 1 :(得分:0)

使用空合并运算符:

Phone = person.Element("PHONE") ?? String.Empty;