I want to generate alphanumeric codes using C#.NET
The first two digits should be alphabet
The next two should be numeric and
the last one should always be alphabet
example: FR30T etc
Loading
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.
Carl SchraderPosted Feb 2, 2009, 8:31 PM
Theo,
Here's one algorithm ... I doubt it is the best/most efficient out there; however, it works.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> alreadyHere = new List<string>(new string[] { "MA33I", "ZZ22C", "OO51A", "YU13O", "SX97Y" });
Console.WriteLine("Alphanumeric generated code: \n\t" + getAlphaNumericCode(alreadyHere) + "\n");
Console.ReadLine();
}
private static readonly string template = "__##_";
static string getAlphaNumericCode(List<string> codesAlreadyInUse)
{
Random alphaRandomGen = new Random(DateTime.Now.Millisecond + DateTime.Now.Second);
Random numericRandomGen = new Random(DateTime.Now.Millisecond + DateTime.Now.Second);
string sANCode = string.Empty;
do
{
for (int i = 0; i < template.Length; i++)
{
int alphaChar = alphaRandomGen.Next(65, 91);
int numericChar = numericRandomGen.Next(48, 58);
if (template[i] == '_')
sANCode += Encoding.ASCII.GetString(new byte[] { (byte)alphaChar });
else
sANCode += Encoding.ASCII.GetString(new byte[] { (byte)numericChar });
}
} while (codesAlreadyInUse.Contains(sANCode));
return sANCode;
}
}
}