繁体   English   中英

为什么我从列表中得到重复的对象 <E> 在C#中?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM