C# LINQ到XML可选元素查询
我正在处理一个现有的XML文档,其结构(部分)如下: “ID”元素并不总是存在,因此我的解决方案是上面的Count()jazz。但我想知道是否有人有更好的方法。我仍然对这些新东西感到满意,我怀疑有比我现在做的更好的方法C# LINQ到XML可选元素查询,c#,linq,linq-to-xml,anonymous-types,C#,Linq,Linq To Xml,Anonymous Types,我正在处理一个现有的XML文档,其结构(部分)如下: “ID”元素并不总是存在,因此我的解决方案是上面的Count()jazz。但我想知道是否有人有更好的方法。我仍然对这些新东西感到满意,我怀疑有比我现在做的更好的方法 有没有更好/更可取的方法来做我想做的事情?在类似的情况下,我使用了一种扩展方法: public static string OptionalElement(this XElement actionElement, string elementName) {
有没有更好/更可取的方法来做我想做的事情?在类似的情况下,我使用了一种扩展方法:
public static string OptionalElement(this XElement actionElement, string elementName)
{
var element = actionElement.Element(elementName);
return (element != null) ? element.Value : null;
}
用法:
id = g.OptionalElement("ID") ?? "none"
那么:
var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
let idEl = g.Element("ID")
select new
{
name = (string)g.element("Name").Value,
id = idEl == null ? "none" : idEl.Value;
};
如果这个函数是barfs,那么FirstOrDefault()
etc可能会有用,否则只需使用扩展方法(如前所述)。在这种情况下,它实际上做了正确的事情
因此,实际上很少需要访问.Value
属性
这就是您的投影所需的全部内容:
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (string) g.Element("ID") ?? "none",
};
如果您希望在匿名类型中使用ID
的值作为整数:
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (int?) g.Element("ID"),
};
ValueOrDefault(这个XElement actionElement、string elementName、string defaultValue)会更整洁,实际上完全没有必要。显式字符串转换操作符已经做到了这一点:有关Hanselman对它的理解,请参见
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (string) g.Element("ID") ?? "none",
};
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (int?) g.Element("ID"),
};