rusty molle rusty molle - 11 months ago 70
C# Question

Error: Producing duplicates C#

So I want to randomly generate unique values into my listbox, however I find that when "\t" is added it produces duplicates. How can I add a tab without generating duplicates in my listbox:

while (lstNumberList.Items.Count < MAX_ITEMS)
{
int value = rnd.Next(101);
if (!lstNumberList.Items.Contains(value))

lstNumberList.Items.Add("\t" + value);

}

Answer Source

Your Contains check is checking for the number without the \t, but then you're adding the item with the \t. So the Contains check will never succeed.

Try this:

int value = rnd.Next(101);
string item = "\t" + value;
if (!lstNumberList.Items.Contains(item))
{
    lstNumberList.Items.Add(item);
}