当我尝试使用where执行查询时,我是Linq的新手并且有一些奇怪的结果。
xml的示例:
<movies>
<movie id="1">
<scenes>
<scene id="1">
<sceneartistsnames>
<sceneartistname>Artist A</sceneartistname>
</sceneartistsnames>
</scene>
<scene id="2">
<sceneartistsnames>
<sceneartistname>Artist B</sceneartistname>
</sceneartistsnames>
</scene>
</scenes>
</movie>
<movie id="10">
<scenes>
<scene id="1">
<sceneartistsnames>
<sceneartistname>Artist B</sceneartistname>
<sceneartistname>Artist A</sceneartistname>
</sceneartistsnames>
</scene>
</scenes>
</movie>
</movies>
现在尝试选择艺术家A所属的所有场景。
Dim Results = From MovieWithArtist In MoviesXML...<scene> _
Where MovieWithArtist.<sceneartistsnames>.<sceneartistname>.Value = "Artist A" _
Select MovieWithArtist
我只得到一个场景回归,我期待两个。 :(
现在,如果我将XML中的第二个场景更改为:
<movie id="10">
<scenes>
<scene id="1">
<sceneartistsnames>
<sceneartistname>Artist A</sceneartistname>
<sceneartistname>Artist B</sceneartistname>
</sceneartistsnames>
</scene>
</scenes>
</movie>
然后我回来了两个场景。
我做错了什么?
谢谢大家。
答案 0 :(得分:1)
为了格式化,我会将其作为单独的答案发布:
这是使用this site转换为VB.Net的Jon的答案。
Private Shared Sub Main()
Dim doc As XDocument = XDocument.Load("movies.xml")
Dim query = doc.Descendants("scene").Where(Function(scene) scene.Elements("sceneartistsnames").Elements("sceneartistname").Any(Function(name) name.Value = "Artist A"))
For Each scene In query
Console.WriteLine(scene)
Next
End Sub
答案 1 :(得分:0)
好吧,我不知道我担心的VB.NET XML语法,但这个C#工作正常:
static void Main()
{
XDocument doc = XDocument.Load("movies.xml");
var query = doc.Descendants("scene")
.Where(scene => scene.Elements("sceneartistsnames")
.Elements("sceneartistname")
.Any(name => name.Value == "Artist A"));
foreach (var scene in query)
{
Console.WriteLine(scene);
}
}
将它转换为对LINQ扩展方法的VB.NET调用应该不难,但我担心你需要其他人(Jared?)来帮助解决特定于XML的语法。
答案 2 :(得分:0)
Jons答案的另一种选择是使用选择多个(多个来自)
var qry = from x in xe.Descendants("scene")
from s in x.Descendants("sceneartistname")
where (string)s == "Artist A"
select string.Format("Movie ID {0} Scene ID {1} : {2}", (int)x.Parent.Parent.Attribute("id"), (int)x.Attribute("id"), (string)s);