C# LINQ to XML中的ISNULL()
从RTRIM(ISNULL([SHORTNAME],'')类似“%john%”的客户中选择* 我想用Linq写这个C# LINQ to XML中的ISNULL(),c#,linq,linq-to-xml,C#,Linq,Linq To Xml,从RTRIM(ISNULL([SHORTNAME],'')类似“%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 = per
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]不为null时,这可以正常工作,如果[SHORTNAME]为null值,则会中断代码并弹出“null引用异常”
请帮帮我…假设你试图避免在没有短名字的地方捡起任何东西
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 : "",
};
或者,您可以使用空合并运算符使所有这些操作变得更简单:
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()
};
使用空合并运算符:
Phone = person.Element("PHONE") ?? String.Empty;
这是行不通的,因为元素返回的是一个XElement,而不是一个字符串。