可能不显示列表中的上一个随机项? [英] Possible to don't display the previous random item from a list?

查看:39
本文介绍了可能不显示列表中的上一个随机项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在做一个小项目,随机生成一个列表项到文本框中。但是它也显示了重复,我不希望它显示。我试图想出一个解决方案,但没有任何运气。

I am doing a little project that randomly generates a list item into a text box. However it also show duplicates which I do not want it to show. I was trying to come up with a solution but didn't have any luck.


基本上我的用户控件和Animal实例中有一个对象动物列表显示随机生成的动物名称或物种:

Basically I have a list of object animal in my User control and Animal instance to display randomly generated Animal name or specie:

List<Animal> animals;
Random random = new Random();
Animal randomAnimal;



在我的构造函数中,我调用上一个用户控件中的列表来填充列表:

In my constructor im calling a list from the previous User control which is used to fill in the list:

public QuestionsUserControl(List<Animal> animals)
{
   this.animals = animals;
}



然后在我的按钮btnDisplayRandomAnimal中显示随机动物:

Then in my button btnDisplayRandomAnimal which displays the random animal:

 randomAnimal= animals[random.Next(animals.Count)];
 string result = Random(random);



这是随机方法:

This is the Random method:

private string Random(Random random)
    {
        if (random.Next(2) == 0)
        {
            txtName.Text = randomAnimal.Name;
            txtName.Clear();
            return randomAnimal.Name;
        }
        else
        {
            txtSpecie.Text = randomAnimal.Specie;
            txtSpecie.Clear();
            return randomAnimal.Specie;
        }
    }



这个工作正常,它在txtName或txtSpecie中显示随机生成的动物及其属性。问题是如何确保相同的名称或物种不会显示两次?任何帮助都会不胜感激。

This works correctly, it displays randomly generated animal and it property either in txtName or txtSpecie. The question is how could I make sure that the same name or specie is not displayed twice? Any help would be appreciated.


谢谢!

推荐答案

我没有密切关注你的代码,但我想我可以提供帮助只需阅读问题描述。

I have not looked closely at your code but I assume I can help just by reading the problem description.

解决问题的一般方法是从列表中删除每个项目(放入列表框)。你需要调整范围因此,不可能两次选择项目。

The general methodology for solving the problem is to remove each item from the list when it is selected (put in the listbox). You need to adjust the range of numbers accordingly. Then it becomes impossible to select an item twice.

如果您需要保留该项目以进行其他处理,那么您可以将所选项目添加到第二个列表。我假设这样是一个类赋值,你不需要这样做,但我不确定。有经验的程序员会将列表框绑定到数据源
,该数据源将是第二个列表。

If you need to retain the item for other processing then you can add the selected items to a second list. I assume this is a class assignment and you don't need to do that but I am not sure. Experienced programmers would bind the listbox to a datasource and that datasource would be the second list.


这篇关于可能不显示列表中的上一个随机项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆