0

所以我需要能够从我的查询返回的一组记录中选择一个随机记录。我在弄清楚如何执行此操作时遇到问题,因为我不确定结果是在哪个容器中提供给我的。我还使用 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当我知道集合中应该有与这些相对应的值时,这些语句被评估为假。

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

有任何想法吗?

4

1 回答 1

0

更新

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

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()

于 2015-02-11T23:41:40.550 回答