Reputation: 1113
I have an XML file and I want to select only one random node. It seems like I'm almost there but the foreach with the var is looping. How do I select only one node and return it?
XML:
<human_check>
<qa>
<q>2 + 2</q>
<a>4</a>
</qa>
<qa>
<q>1 + 2</q>
<a>3</a>
</qa>
<qa>
<q>6 + 3</q>
<a>9</a>
</qa>
<qa>
<q>3 + 5</q>
<a>7</a>
</qa>
</human_check>
C#
public class human_check
{
public static string get_q()
{
try
{
string h = string.Empty;
Random rnd = new Random();
XDocument questions = XDocument.Load(@"C:\Users\PETERS\Desktop\human_check.xml");
var random_q = from q in questions.Descendants("qa")
select new
{
question = q.Descendants("q").OrderBy(r => rnd.Next()).First().Value
};
foreach (var rq in random_q)
{
h = rq.question.ToString();
}
return h;
}
catch (Exception ex)
{
throw ex;
}
}
}
Thanks in advance,
EP
Upvotes: 2
Views: 1300
Reputation: 3125
Instead of setting up an ordering you could just pick a random element.
var qas = questions.Descendants("qa");
int qaCount = qas.Count();
h = qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value;
Upvotes: 4
Reputation: 5080
var random_q = (from q in questions.Descendants("qa")
select q).OrderBy(r => rnd.Next()).First();
h = random_q.Descendants("q").SingleOrDefault().Value.ToString();
Upvotes: 3