gpt4 book ai didi

c# - 使用 LINQ 选择随机 XML 节点

转载 作者:数据小太阳 更新时间:2023-10-29 02:28:16 26 4
gpt4 key购买 nike

我是 LINQ 的新手,遇到了问题。我有一个看起来像这样的文件:

<?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 语句?

最佳答案

您能否通过 Random.Next() 对图库中的图像进行排序,然后选择第一个元素。

我不太了解 linq2xml,但这是我想出的

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 thing 一起工作。

关于c# - 使用 LINQ 选择随机 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2061338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com