使用哪种集合类型?
我有一个场景,我有一个类列表,我想混淆顺序。例如:
private List<Question> myQuestions = new List<Question>();
因此,鉴于现在填充了一组数据,我想混合顺序。我的第一个想法是创建一个从 1 到 myQuestions.Count 的整数集合,为每个问题随机分配一个,然后按顺序循环遍历它们;但是,我似乎找不到合适的集合类型来用于此目的。我的意思的一个例子是这样的:
for (int i = 0; i <= myQuestions.Count -1; i++)
tempCollection[i] = myQuestions[rnd.Next(myQuestions.Count-1)];
但我不确定 tempCollection 应该是什么 - 它只需要是一个我可以在使用时删除的单个值。有人对使用哪种类型有任何建议,或者有更好的方法吗?
I have a scenario where I have a list of classes, and I want to mix up the order. For example:
private List<Question> myQuestions = new List<Question>();
So, given that this is now populated with a set of data, I want to mix up the order. My first thought was to create a collection of integers numbered from 1 to myQuestions.Count, assign one at random to each question and then loop through them in order; however, I can’t seem to find a suitable collection type to use for this. An example of what I mean would be something like this:
for (int i = 0; i <= myQuestions.Count -1; i++)
tempCollection[i] = myQuestions[rnd.Next(myQuestions.Count-1)];
But I’m not sure what tempCollection should be – it just needs to be a single value that I can remove as I use it. Does anyone have any suggestions as to which type to use, or of a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您将结果复制到新的
List
中,然后随机播放该列表。但是,我会使用 Fisher-Yates shuffle 而不是那个你已经给了这里。此站点上有大量 C# 示例。
例如,您可能会这样做:
I suggest you copy the results into a new
List<Question>
and then shuffle that list.However, I would use a Fisher-Yates shuffle rather than the one you've given here. There are plenty of C# examples of that on this site.
For example, you might do:
您可以使用 Linq 并按随机值排序:
You could use Linq and order by a random value:
temp 集合应与 myQuestions 类型相同。
我还建议更改您的代码:
到
做同样的事情,但这是大多数程序员的做法,因此它将使您的代码更易于阅读。
temp Collection should be same type as myQuestions.
I would also suggest a change in your code:
to
Does the same thing, but this is how most programers do it so it will make your code simpler to read.