我正在从cookie中读取一个guid,用linq随机化一个列表,如果cookie为null,我会生成新的guid并将其保存到cookie然后使用它,但列表不是随机的。
为什么?
var questions = IZBSC.UI.Components.Utility.GetQuestionBank(Model.ExamId);
var random = "";
if (Request.Cookies["Rnd"] == null)
{
random = Guid.NewGuid().ToString();
HttpCookie cookie = new HttpCookie("Rnd", random.ToString())
{
HttpOnly = true,
Expires = DateTime.Now.AddDays(1)
};
Response.Cookies.Add(cookie);
}
else
{
random= Request.Cookies["Rnd"].Value;
}
@foreach (var question in questions.OrderBy(q =>random).Take(questions.Count).ToList())
{...}
答案 0 :(得分:2)
我想你可能想要存储种子而不是guid并使用类似于(工作示例)的代码:
var list = new List<int>(){1, 2, 3, 4, 5, 6, 7, 8};
var seed = 3; // CREATE THIS RANDOM NUMBER AND STORE IT INSTEAD OF THE GUID
var rnd = new Random(seed);
var ordered = list.OrderBy(r => rnd.Next());
foreach(var item in ordered)
{
Console.WriteLine(item);
}
所以,你的代码看起来像是:
var questions = IZBSC.UI.Components.Utility.GetQuestionBank(Model.ExamId);
var seed;
if (Request.Cookies["Rnd"] == null)
{
seed = new Random().Next();
HttpCookie cookie = new HttpCookie("Rnd", seed.ToString())
{
HttpOnly = true,
Expires = DateTime.Now.AddDays(1)
};
Response.Cookies.Add(cookie);
}
else
{
seed = int.Parse(Request.Cookies["Rnd"].Value);
}
var random = new Random(seed);
@foreach (var question in questions.OrderBy(q =>random.Next()))
{...}
答案 1 :(得分:1)
您在OrderBy
声明中使用了相同的值,这就是为什么您以相同的顺序获取商品的原因。
您可以使用类似questions.OrderBy(q =>Guid.NewGuid())
之类的内容对列表进行随机播放,但是您希望为后续请求保留相同的种子值,因此您应该使用Random
类。