使用LINQ to选择一个随机的XML节点 [英] Using LINQ to select a random XML node
问题描述
我是新来的LINQ和我有一个问题。我有一个看起来像这样的文件:
I'm new to LINQ and am having a problem. I have a file that looks something like this:
<?xml version="1.0" encoding="utf-8" ?>
<Galleries>
<Gallery ID="10C31804CEDB42693AADD760C854ABD" Title="Test1">
<Description>The first test gallery. Picture of a cat and Wilford Brimley. Can you tell the difference?</Description>
<Images>
<Image Title="t1Image1" FileName="tcats.jpg" />
<Image Title="t1Image2" FileName="twb.jpg" />
</Images>
</Gallery>
<Gallery ID="0420EC15405B488E1E0F157AC823A6" Title="Test2">
<Description>The second test gallery. A large image of Wilford Brimley and various cats. The cats will be on the right.</Description>
<Images>
<Image Title="t2Image1" FileName="wilfordbrimley.jpg" />
</Images>
</Gallery>
</Galleries>
不管怎样,我知道我要的画廊的ID,但我想选择的图像之一随机的。是否有一个LINQ语句可以做到这一点?
Anyway, I know the ID of the Gallery I want, but I want to choose one of the images at random. Is there a LINQ statement that can do this?
推荐答案
您可以通过Random.Next才能在多媒体的图像(),然后选择出来的第一个元素。
Can you order the Images in the gallery by Random.Next() then select out the first element.
我不知道很多关于linq2xml但这里是我想出了
I dont know much about linq2xml but here's what i came up with
static void Main(string[] args)
{
Random rnd = new Random();
XDocument galleries = XDocument.Load(@"C:\Users\John Boker\Documents\Visual Studio 2008\Projects\ConsoleApplication1\ConsoleApplication1\Galleries.xml");
var image = (from g in galleries.Descendants("Gallery")
where g.Attribute("ID").Value == "10C31804CEDB42693AADD760C854ABD"
select g.Descendants("Images").Descendants("Image").OrderBy(r=>rnd.Next()).First()).First();
Console.WriteLine(image);
Console.ReadLine();
}
我敢肯定的选择可以不同做了很多,但是这就是我这样做,使之与random.next事工作。
I'm sure the selecting could be done a lot differently, but that's what i did to make it work with the random.next thing.
这篇关于使用LINQ to选择一个随机的XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!