【问题标题】:Need to pick a random record from query results需要从查询结果中选择一条随机记录
【发布时间】:2015-04-12 12:53:11
【问题描述】:

所以我需要能够从我的查询返回的一组记录中选择一条随机记录。我在弄清楚如何执行此操作时遇到问题,因为我不确定结果是在哪个容器中提供给我的。我还使用 EntitySpaces 进行数据库持久性,因此大部分数据库交互性都来自那里。

我已经在下面粘贴了应该执行此操作的方法,以及我遇到问题的伪代码。

    protected void btnChoose_Click(object sender, EventArgs e)
{

    DateTime? dateFrom = null;
    DateTime? dateTo = null;

    if (!string.IsNullOrWhiteSpace(dtDateTo.Text))
    {
        dateFrom = dtDateFrom.Text.ToDateTime().Value;
    }
    if (!string.IsNullOrWhiteSpace(dtDateTo.Text))
    {
        dateTo = dtDateTo.Text.ToDateTime().Value.EndOfDay();
    }

    EmployeeRecognitionCollection erc = EmployeeRecognitionCollection.GetAllCards(dateFrom, dateTo, null, null);

    --> I need to figure out what 'erc' actually is so I can figure out how to use Random() appropriately 

    --> I've already verified that erc ends up containing the records that match the criteria in the query (in this case it's just a date range)

}

非常感谢任何帮助。由于我们使用了 EntitySpaces,我什至不确定此时谷歌应该做什么,以及这似乎使几乎所有正常的解决方案都不起作用。

谢谢。

更新:

这就是我目前所想出的。现在的问题是 if 语句在我知道集合中应该有对应于这些值的值时被评估为 false。

    EmployeeRecognitionCollection erc = EmployeeRecognitionCollection.GetAllCards(dateFrom, dateTo, null, null);

    int minRecords = 0;
    int maxRecords = 0;

    if (erc[0].ToInteger().HasValue)
    {
        minRecords = erc[0].ToInteger().Value;
    }
    if (erc[erc.Count() - 1].ToInteger().HasValue)
    {
        maxRecords = erc[erc.Count() -1].ToInteger().Value;
    }

    Random r = new Random();
    int winner = r.Next(minRecords, maxRecords);

    EmployeeRecognition er = erc[winner];

有什么想法吗?

【问题讨论】:

  • 您使用什么语言?请为该语言添加标签。
  • 哎呀,对不起。添加了 C# 标签。

标签: c# sql random entityspaces


【解决方案1】:

更新

我无法完全理解您在更新后的代码中想要实现的目标,但是,这是我对应该如何编写的最佳猜测,请尝试一下:

Random r = new Random();
int winner = r.Next(0, erc.Count()-1);
EmployeeRecognition er = erc[winner];

从名称EmployeeRecognitionCollection看来,它是一个集合。如果可以调试,使用 quickwatch 需要了解的是它是否支持索引器。即可以做 erc[i].如果是,那么在索引器上使用 Random 就相当简单了。

如果它不支持索引器,您可能想知道它是否提供了 Count 属性。这样你就可以获得枚举器,将它推进 i 次,其中 i 是 0 到 Count-1 之间的随机数。要提前,您需要致电

erc.GetEnumerator().MoveNext()

【讨论】:

  • 好的,所以我将到目前为止所做的添加到上面的原始项目中。感谢您对索引器的建议。
猜你喜欢
  • 2019-07-15
  • 2010-10-18
  • 2017-06-28
  • 2016-05-21
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多