[英]why I get repeated object from List<E> in C#?
這是我的問題函數,我將數據集合發送到ShuffledList函數以便一次獲取一行
private void nextQuestion_Question()
{
ql1 = ShuffleList(ql1);
currentQuestion_List = ql1.ElementAt(0);
//ql1.RemoveAt(0);
txtQ.Text = currentQuestion_List.text;
btnA.Text = currentQuestion_List.a;
btnB.Text = currentQuestion_List.b;
btnC.Text = currentQuestion_List.c;
btnD.Text = currentQuestion_List.d;
}
但是這個函數有時會返回重復的對象
private List<E> ShuffleList<E>(List<E> inputList)
{
List<E> randomList = new List<E>();
Random r = new Random();
int randomIndex = 0;
while (inputList.Count>0)
{
randomIndex = r.Next(inputList.Count); //Choose a random object in the list
randomList.Add(inputList[randomIndex]); //add it to the new, random list
inputList.RemoveAt(randomIndex); //remove to avoid duplicates
}
return randomList; //return the new random list
}
請注意,我正在嘗試制作多選游戲,並且效果很好,但有時會重復同樣的問題,如果您能幫助我解決這個問題,
我認為您在可重復洗牌中遇到了問題。 嘗試存儲一次隨機播放的列表,以防止在游戲過程中兩次生成相同的問題位置時發生情況
bool listShuffled = false;
private void nextQuestion_Question()
{
if(!listShuffled){
listShuffled = true;
ql1 = ShuffleList(ql1);
}
currentQuestion_List = ql1.ElementAt(0);
//ql1.RemoveAt(0);
txtQ.Text = currentQuestion_List.text;
btnA.Text = currentQuestion_List.a;
btnB.Text = currentQuestion_List.b;
btnC.Text = currentQuestion_List.c;
btnD.Text = currentQuestion_List.d;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.