【问题标题】:Make a c# list show the same item for the whole day and then another random element for the next day?让一个 c# 列表一整天显示相同的项目,然后在第二天显示另一个随机元素?
【发布时间】:2013-08-21 17:02:24
【问题描述】:

现在的一个问题是我从列表中随机挑选元素并将它们展示给用户,这些元素随着 asp.net 的每次页面刷新而变化。

但是我想一整天显示一个元素,然后在第二天显示另一个元素,依此类推。

我随机挑选列表元素的代码是:

  public static List<T> Shuffle<T>(this IList<T> list)
{
    RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
    int n = list.Count;
    while (n > 1)
    {
        byte[] box = new byte[1];
        do provider.GetBytes(box);
        while (!(box[0] < n * (Byte.MaxValue / n)));
        int k = (box[0] % n);
        n--;
        T value = list[k];
        list[k] = list[n];
        list[n] = value;
    }

    return list.ToList();
}

【问题讨论】:

  • 您想为不同的用户使用不同的随机序列,还是对特定日期的所有用户使用相同的随机序列?
  • 所有用户将在一天内看到相同的记录

标签: c# asp.net list timer


【解决方案1】:

您可以使用Random 类来打乱您的列表,并根据当天提供seed 值:

public static void Shuffle<T>(this IList<T> list)  
{  
    Random rng = new Random(unchecked((int)DateTime.Today.Ticks));  
    int n = list.Count;  
    while (n > 1) {  
        n--;  
        int k = rng.Next(n + 1);  
        T value = list[k];  
        list[k] = list[n];  
        list[n] = value;  
    }  
}

因为您将在全天使用相同的种子初始化 Random 实例,所以您将获得由 rng.Next 方法生成的相同数字序列。

要在同一天内每次刷新都获得相同的单个项目,您无需重新整理您的收藏:

public static T GetRandomItemForToday<T>(this IList<T> list)  
{  
    Random rng = new Random(unchecked((int)DateTime.Today.Ticks));  
    return list[rng.Next(list.Count)];
}

【讨论】:

  • BUT Random 不采用双精度作为参数。
  • 嗨,我们可以比较(取模数)随机数和列表的计数吗?无法将“System.Random”类型的对象转换为“System.IConvertible”类型。
  • 试过了,它似乎仍然在改变页面刷新和导航到不同页面的值
  • 在调用中传递给该方法的集合是否相同?
猜你喜欢
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2021-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多