如何在 C# 中使用 LINQ 读取 Xml 文件
我有一个 XML 文件,就像
<root>
<Child val1="1" val2="2"/>
<Child val1="3" val2="4"/>
<Child val1="5" val2="6"/>
<Child val1="7" val2="8"/>
<Child val1="9" val2="10"/>
<Child val1="11" val2="12"/>
<Child val1="13" val2="14"/>
</root>
我需要将 val1
和 val2
的属性值读取到 List
生成的列表将包含
{ "1" , "2" , "3" , ........ ,"13" , "14" }
这是我的示例代码:
XDocument XD = XDocument.Load(Application.StartupPath + "\\foo.xml");
List<String> l_lstTemp = XD.Descendants("Child")
.Select(X => new List<String> { X.Attribute("val1").Value,
X.Attribute("val2").Value })
.SelectMany(X => X)
.Distinct()
.ToList();
有什么方法可以使用 Select
而不是 selectMany
来执行此操作?
如何修改我现有的表达式
?
I'm having an XML file like
<root>
<Child val1="1" val2="2"/>
<Child val1="3" val2="4"/>
<Child val1="5" val2="6"/>
<Child val1="7" val2="8"/>
<Child val1="9" val2="10"/>
<Child val1="11" val2="12"/>
<Child val1="13" val2="14"/>
</root>
i need to read the attribute values of val1
and val2
to a List<String>
the resulting list will contain
{ "1" , "2" , "3" , ........ ,"13" , "14" }
Here is my sample code:
XDocument XD = XDocument.Load(Application.StartupPath + "\\foo.xml");
List<String> l_lstTemp = XD.Descendants("Child")
.Select(X => new List<String> { X.Attribute("val1").Value,
X.Attribute("val2").Value })
.SelectMany(X => X)
.Distinct()
.ToList();
is there any way to do this using Select
instead of selectMany
?
How to modify my existing expression
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SelectMany
正在做您想要的事情 - 它将结果从字符串列表序列展平为单个字符串序列。为什么您想要采用准确表达您需要的工作代码并更改它?诚然,您可以通过稍微不同地使用
SelectMany
来简化它,并使用数组而不是列表来缩短一些时间:SelectMany
is doing exactly what you want here - it's flattening the result from a sequence of lists of strings to a single sequence of strings. Why would you want to take working code which expresses exactly what you need and change it?Admittedly you can simplify it somewhat by using
SelectMany
slightly differently, and using an array instead of a list to shorten things a bit too::您的问题场景正是 SelectMany 的用途,因此我认为我们可能尝试消除它的任何事情只会使事情变得复杂。 :)
初始的 .Select 返回 IEnumerable 的结果,并且没有 .SelectMany 我们会得到:
.SelectMany 采用 IEnumerable 会将初始结果“压平”到另一个 IEnumerable 中,让您得到您想要的结果:
这是一篇很棒的帖子更好的描述 LINQ SelectMany 运算符的直观外观。
Your problem scenario is exactly what SelectMany is there for so I think anything we might try to do to eliminate it would just complicate things. :)
The initial .Select is returning a result of IEnumerable's and without the .SelectMany we'd get:
.SelectMany takes an IEnumerable will 'flatten' the initial results into another IEnumerable leaving you with what you want:
Here is a great post with a much better description A Visual Look at the LINQ SelectMany Operator.