How do I check if string exist in list?
I'm working out on a random 4 length number that won't repeat so I'm trying to do a list with the numbers already tried then check if the number is already in the list if not add else generate another one.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sergio FonsecaPosted Feb 5, 2008, 6:08 PM
AlanPosted Feb 5, 2008, 12:54 PM
Try this code:
using System;
using System.Collections.Generic;
class Program
{
static Random rand = new Random();
static void Main() numbers = new List(x);
{
Console.Write ("How many unique 4 digit random numbers do you want to generate? : ");
int x = int.Parse(Console.ReadLine());
List
numbers.Add(rand.Next(0,10000)); // first one must be unique
bool unique;
int num = 0;
for (int i = 1; i < x; i++)
{
unique = false;
while(!unique)
{
num = rand.Next(0,10000);
if (numbers.IndexOf(num) == -1) // if unique
{
numbers.Add(num);
unique = true;
}
}
}
Console.WriteLine("\nThe {0} random numbers are :\n", x);
foreach(int number in numbers)
{
Console.WriteLine(number.ToString("D4"));
}
Console.ReadKey();
}
}