[英]Linq query on Xdocument returns "System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String]
I'm using the following XML: 我正在使用以下XML:
<?xml version="1.0" encoding="windows-1252"?>
<hexML>
<head>
<title><![CDATA[ ]]></title>
<description><![CDATA Releases XML]]></description>
<flastmod date="2014-09-24T16:34:23 CET"/>
</head>
<body>
<press_releases>
<press_release id="1796256" joint_id="383320" language="fr" type="5">
<published date="2014-06-19T11:55:09 CET"/>
<categories>
<category id="75" label="French" keywords="language"/>
</categories>
<headline><![CDATA[Test Release for Website 3]]></headline>
<ingress></ingress>
<location href="http://rthrthrthrtrt.com/test.xml"/>
</press_release>
</press_releases>
</body>
</hexML>
I'm trying to get datas through this block of code: 我正在尝试通过这段代码获取数据:
cp[cpt, 0] = (from c in xdoc.Descendants("press_release")
where (int)c.Attribute("id") == r
select c.Element("headline").Value).Single();
cp[cpt, 1] = (from c in xdoc.Descendants("press_release")
where (int)c.Attribute("id") == r
select (c.Element("published").Attribute("date").Value)).ToString();
cp[cpt, 3] = (from c in xdoc.Descendants("press_release")
where (int)c.Attribute("id") == r
select c.Element("location").Attribute("href").Value).ToString();
The first instruction returns correctly : Test Release for website 3. On the other hand , the 2 others returns "System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String]" instead. 第一条指令正确返回:网站3的测试版本。另一方面,另外两条返回“System.linq.Enumerable + WhereSelectEnumerableIterator'2 [system.XML.Linq.Xelement,System.String]”。
Thank for your help 谢谢您帮忙
NB: I'm using .NET V3.5 注意:我使用的是.NET V3.5
Yes, that's because you've calling ToString()
directly on a query for your second and third values - whereas in the first operation, you're calling Single()
which will return a single string value. 是的,那是因为您直接在查询第二个和第三个值时调用ToString()
- 而在第一个操作中,您调用的是Single()
,它将返回单个字符串值。
Basically, don't call ToString()
on queries. 基本上,不要在查询上调用ToString()
。 If you want a single value, use Single()
, First()
etc. If you want multiple values, iterate over them and do what you want with each of them in turn - or join them together in some appropriate fashion. 如果你想要一个单独的值,可以使用Single()
, First()
等。如果你想要多个值,迭代它们并依次对它们进行所需的操作 - 或者以适当的方式将它们连接在一起。
Note that this has nothing to do with LINQ to XML - it's just what LINQ to Objects does: 请注意,这与LINQ to XML无关 - 它正是LINQ to Objects所做的:
using System;
using System.Linq;
class Test
{
static void Main()
{
string[] values = { "a", "b", "c" };
var query = values.Where(x => true);
Console.WriteLine(query);
Console.WriteLine(string.Join(";", query));
}
}
Output: 输出:
System.Linq.Enumerable+WhereArrayIterator`1[System.String]
a;b;c
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.