C# Unique Random Integer Create
-
Saturday, December 26, 2009 9:02 AM
public static int RandomCreate(){
Random r = new Random();
return r.Next(0,10);
}
but I want create unique integers ? How I do this?
All Replies
-
Saturday, December 26, 2009 9:29 AM
-
Saturday, December 26, 2009 9:36 AM
Hope the following link will help you.
Unique Random Number Generator Class (C# .NET)
I don't understand anything from the code.Can you give sample me? -
Saturday, December 26, 2009 9:48 AM
try this
Methodpublic ArrayList RandomNumbers(int iFromNum, int iToNum, int iNumOfItem) { ArrayList lstNumbers = new ArrayList(); Random rndNumber = new Random(); int number = rndNumber.Next(iFromNum, iToNum + 1); lstNumbers.Add(number); int count = 0; do { number = rndNumber.Next(iFromNum, iToNum + 1); if (!lstNumbers.Contains(number)) { lstNumbers.Add(number); } count++; } while (count <= iNumOfItem); return lstNumbers; }
Sample Code
---------------
private void Form2_Load(object sender, EventArgs e) { ArrayList ar = RandomNumbers(11111, 999999999, 20); for (int iLoop = 0; iLoop < ar.Count; iLoop++) { textBox1.Text = textBox1.Text + ar[iLoop] + "\r\n"; } }
u can loop through the array and get the numbershope this helped...
Narayanan Dayalan -------- Please "Mark As Answer", if my answer works well with ur Query- Marked As Answer by Bin-ze ZhaoModerator Monday, December 28, 2009 9:42 AM
-
Saturday, December 26, 2009 7:12 PMWhats the overall scenario ? Of course in the range of 0-10 you cannot get unique numbers.If you want to use this unique number and store it in DB then better use the Identity property of DB itself to generate unique numbers.If you have to do at class lever then you can either create a new GUID (unique identifier) or you can declare a global static variable and increment its value just before accessing it.
And the code sample provided will also help you , just that in place of ArrayList use List<Int32> . Its recommended to use List<> if you are programming in .Net framework 2.0 or above.

