its*_*att 14 c# linq anonymous-types linq-to-xml
我正在使用现有的XML文档,其结构(部分)如下:
<Group>
<Entry>
<Name> Bob </Name>
<ID> 1 </ID>
</Entry>
<Entry>
<Name> Larry </Name>
</Entry>
</Group>
Run Code Online (Sandbox Code Playgroud)
我正在使用LINQ to XML来查询XDocument以检索所有这些条目,如下所示:
var items = from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string)g.element("Name").Value,
id = g.Elements("ID").Count() > 0 ? (string)g.Element("ID").Value : "none"
};
Run Code Online (Sandbox Code Playgroud)
"ID"元素并不总是存在,因此我对此的解决方案是上面的Count()爵士乐.但我想知道是否有人有更好的方法来做到这一点.我仍然对这些新东西感到满意,我怀疑可能有更好的方法来做到这一点,而不是我现在正在做的事情.
有没有更好/更优选的方式来做我想要的?
Jac*_*ter 23
XElement实际上有一些有趣的显式转换运算符,在这种情况下做正确的事情.
因此,您很少需要访问该.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",
};
Run Code Online (Sandbox Code Playgroud)
如果您更喜欢ID在匿名类型中使用整数值:
var items =
from g in xDocument.Root.Descendants("Group").Elements("Entry")
select new
{
name = (string) g.Element("Name"),
id = (int?) g.Element("ID"),
};
Run Code Online (Sandbox Code Playgroud)