C# LINQ到XML-检查是否为空?
我已经使用LINQ大约两天了,请耐心等待 这是我目前的代码C# LINQ到XML-检查是否为空?,c#,xml,linq,linq-to-xml,C#,Xml,Linq,Linq To Xml,我已经使用LINQ大约两天了,请耐心等待 这是我目前的代码 _resultList = ( from item in _documentRoot.Descendants("MyItems") select new MyClass { XMLID = item.Attribute("id").Value }).ToList<MyClass>(); 大多数元素都有一个“id”属性,它们被成功地添加到列表中。 然而,有些人没有“id”。 对
_resultList = (
from
item in _documentRoot.Descendants("MyItems")
select
new MyClass
{
XMLID = item.Attribute("id").Value
}).ToList<MyClass>();
大多数元素都有一个“id”属性,它们被成功地添加到列表中。
然而,有些人没有“id”。
对于这些,我希望“id”只是一个空字符串
在尝试访问该属性之前,如何检查该属性是否存在?
谢谢您可以将其存储在一个变量中,并根据该变量是否为null定义XMLID属性的值:
from item in _documentRoot.Descendants("MyItems")
let idAttr = item.Attribute("id")
select new MyClass
{
XMLID = idAttr != null ? idAttr.Value : string.Empty
}).ToList<MyClass>();
您可以将其存储在变量中,并根据此变量是否为null定义XMLID属性的值:
from item in _documentRoot.Descendants("MyItems")
let idAttr = item.Attribute("id")
select new MyClass
{
XMLID = idAttr != null ? idAttr.Value : string.Empty
}).ToList<MyClass>();
您不需要将属性存储在其他变量中。若属性不在那个里,那个么将返回null。使用power of,您可以提供默认值-空字符串:
from item in _documentRoot.Descendants("MyItems")
select new MyClass {
XMLID = (string)item.Attribute("id") ?? ""
}
您不需要将属性存储在其他变量中。若属性不在那个里,那个么将返回null。使用power of,您可以提供默认值-空字符串:
from item in _documentRoot.Descendants("MyItems")
select new MyClass {
XMLID = (string)item.Attribute("id") ?? ""
}