Skip to main content
 首页 » 编程设计

c#之使用哪种集合类型

2024年02月03日31mfryf

我有一个场景,其中有一个类列表,我想打乱顺序。例如:

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 应该是什么——它只需要是一个我可以在使用时删除的值。有人对使用哪种类型或更好的方法有任何建议吗?

请您参考如下方法:

我建议您将结果复制到新的 List<Question> 中然后洗牌。

但是,我会使用 Fisher-Yates shuffle而不是你在这里给的那个。此站点上有大量 C# 示例。

例如,您可能会这样做:

// Don't create a new instance of Random each time. That's a detail 
// for another question though. 
Random rng = GetAppropriateRandomInstanceForThread(); 
 
List<Question> shuffled = new List<Question>(myQuestions); 
for (int i = shuffled.Count - 1; i > 0; i--) 
{ 
    // Swap element "i" with a random earlier element it (or itself) 
    int swapIndex = rng.Next(i + 1); 
    Question tmp = shuffled[i]; 
    shuffled[i] = shuffled[swapIndex]; 
    shuffled[swapIndex] = tmp; 
}