C# 从linq到xml仅选择一个随机节点
我有一个XML文件,我只想选择一个随机节点。看起来我就快到了,但是带有var的foreach正在循环。如何仅选择一个节点并返回它 XML: 提前感谢,C# 从linq到xml仅选择一个随机节点,c#,xml,linq,var,C#,Xml,Linq,Var,我有一个XML文件,我只想选择一个随机节点。看起来我就快到了,但是带有var的foreach正在循环。如何仅选择一个节点并返回它 XML: 提前感谢, EP您可以选择一个随机元素,而不是设置排序 var qas = questions.Descendants("qa"); int qaCount = qas.Count(); h = qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value; public class human_ch
EP您可以选择一个随机元素,而不是设置排序
var qas = questions.Descendants("qa");
int qaCount = qas.Count();
h = qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value;
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;
}
}
}
var random_q = (from q in questions.Descendants("qa")
select q).OrderBy(r => rnd.Next()).First();
h = random_q.Descendants("q").SingleOrDefault().Value.ToString();
var qas = questions.Descendants("qa");
int qaCount = qas.Count();
h = qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value;