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>
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?
Can you order the Images in the gallery by Random.Next() then select out the first element.
I dont know much about linq2xml but here's what i came up with
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.
Here are a couple solutions that rely on computing the number of
Image
nodes; not terribly efficient, but I don't think you can do better since many Linq collection types are exposed asIEnumerable
.I do not recommend using the selected answer as it uses a sort which is
O(n log n)
wheren
is the number of images in the selected gallery. You can select a random item from a list inO(1)
time. Thus, I would use the following:Here I am using: