I do not recommend using the selected answer, since it uses the O(n log n) sort, where n is the number of images in the selected gallery. You can select a random item from a list in O(1) time. So I would use the following:
using(StreamReader sr = new StreamReader(File.Open(path, FileMode.Open))) { XDocument galleries = XDocument.Load(sr); string id = "10C31804CEDB42693AADD760C854ABD"; var query = (from gallery in galleries.Descendants("Galleries") .Descendants("Gallery") where (string)gallery.Attribute("ID") == id select gallery.Descendants("Images") .Descendants("Image") ).SingleOrDefault(); Random rg = new Random(); var image = query.ToList().RandomItem(rg); Console.WriteLine(image.Attribute("Title")); }
Here I use:
static class ListExtensions { public static T RandomItem<T>(this List<T> list, Random rg) { if(list == null) { throw new ArgumentNullException("list"); } if(rg == null) { throw new ArgumentNullException("rg"); } int index = rg.Next(list.Count); return list[index]; } }
source share