【问题标题】:select only one random node from linq to xml从 linq 到 xml 只选择一个随机节点
【发布时间】:2012-09-11 08:26:39
【问题描述】:

我有一个 XML 文件,我只想选择一个随机节点。好像我快到了,但是带有 var 的 foreach 正在循环。如何只选择一个节点并返回?

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;
        }
    }

}

提前致谢,

EP

【问题讨论】:

    标签: c# xml linq var


    【解决方案1】:

    您可以只选择一个随机元素,而不是设置排序。

    var qas = questions.Descendants("qa");
    int qaCount = qas.Count();
    h = qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value;
    

    【讨论】:

      【解决方案2】:
      var random_q = (from q in questions.Descendants("qa")
                      select q).OrderBy(r => rnd.Next()).First();
      
      h = random_q.Descendants("q").SingleOrDefault().Value.ToString();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-07
        • 1970-01-01
        相关资源
        最近更新 更多