代码:
XElement elem = XElement.Load("http://localhost:54002/sample.xml");
IEnumerable<List<String>> elem1 = (from member in elem.Elements("member")
where (String.Equals(member.Attribute("class").Value, "prem", StringComparison.OrdinalIgnoreCase))
select member.Elements("customer").Select(f => f.Value.ToString()).ToList());
IEnumerable<string> out; // required output format
foreach (List<string> temp in elem1)
{
out = temp;
}
sample.xml中
<root>
<member class="gold">
<customer>cust3</customer>
<customer>cust5</customer>
<customer>cust8</customer>
<customer>cust1</customer>
</member>
<member class="prem">
<customer>cust5</customer>
<customer>cust1</customer>
<customer>cust3</customer>
<customer>cust2</customer>
</member>
<member class="silver">
<customer>cust5</customer>
<customer>cust8</customer>
<customer>cust1</customer>
<customer>cust4</customer>
</member>
</root>
我需要以IEnumerable字符串格式返回linq输出而不使用foreach循环。简单来说,linq查询本身应返回所需的输出。
答案 0 :(得分:1)
您可以在LINQ流利语法中使用SelectMany()
直接返回List<string>
:
IEnumerable<string> _out; // required output format
_out = elem.Elements("member")
.Where(o => string.Equals(o.Attribute("class").Value, "prem", StringComparison.OrdinalIgnoreCase))
.SelectMany(o => o.Elements("customer"))
.Select(o => o.Value);
或者在查询语法中使用from
子句两次返回相同的内容,例如:
IEnumerable<string> _out; // required output format
_out = (from member in elem.Elements("member")
where String.Equals(member.Attribute("class").Value, "prem", StringComparison.OrdinalIgnoreCase)
from customer in member.Elements("customer")
select customer.Value);
<强> Dotnetfiddle Demo
强>