【问题标题】:why I get repeated object from List<E> in C#?为什么我从 C# 中的 List<E> 得到重复的对象?
【发布时间】:2017-04-19 05:32:21
【问题描述】:

这是我的问题函数,我将数据集合发送到 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
    }

请注意,我正在尝试制作一个多选游戏,它运行良好,但有时会重复相同的问题 请帮我解决这个问题

【问题讨论】:

  • 您的 ShuffleList 有缺陷。它作为就地 suffle 交换元素更有效;您应该在应用程序的生命周期中使用相同的随机对象;适当的 shuffle 向后循环,以便每个元素仅交换一次。然后每局只洗一次
  • 我也在尝试按照你说的做,但它对我不起作用可以纠正吗?
  • 这里有很多很多答案展示了如何正确地洗牌

标签: c# list oop


【解决方案1】:

我认为你的重复洗牌有问题。尝试存储一次打乱列表,以防止在游戏会话期间两次生成相同的问题位置的情况

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;

}

【讨论】:

  • 亲爱的@Nigrimmist 它总是返回相同的对象
  • 您是否需要每个下一个问题都是独一无二的?如果是 - 您需要使用队列。如果是随机的 - 只针对用户 new Random().Next(0,ql1.count-1) 而不是 0 el pos。
  • 我希望每个问题随机出现一次
  • 好的,这意味着你需要随机播放,然后 - 一个接一个。队列msdn.microsoft.com/en-us/library/7977ey2c(v=vs.110).aspx是你需要的。
猜你喜欢
  • 1970-01-01
  • 2017-05-23
  • 2012-11-10
  • 2017-01-21
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 2021-07-22
相关资源
最近更新 更多