Using LINQ to generate a random confirmation number
Igor Ostrovsky recently published a great blog post about 7 tricks for using LINQ to simplify your programs. Posts like this really make me re-evaluate how I am writing my code in C# 3.0. For example, I had written a piece of code for my current project that generates a random confirmation number for a reservation system. After reading Igor's post, I built off one of his examples and refactored my code to use LINQ to build my confirmation number. I must admit, the refactored code is much more elegant:
private static readonly char[] AVAILABLE_CHARS =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890123456789".ToCharArray();
private static string GenerateConfirmationNumber(int length)
{
int lastIndex = AVAILABLE_CHARS.length - 1;
Random rand = new Random();
var confNbr =
Enumerable.Repeat<int>(0, length) // loop N times
.Select<int, int>(loopNbr => rand.Next(0, lastIndex)) // get a random index
.Select<int, char>(index => AVAILABLE_CHARS[index]) // pull a char
.ToArray(); // project the results to a char[]
return new String(confNbr);
}
I think it's important to remember that LINQ is much, much more than just LINQ-to-SQL (which is what most people immediately think of when you refer to LINQ). In fact, none of the examples in Igor's post have anything to do with SQL. Take a look at his post (and other LINQ examples online) and hopefully it will give you ideas on how to code using more of a dynamic language type syntax.
Wednesday, May 21, 2008 9:42:57 AM (Eastern Standard Time, UTC-05:00)
.Net | C# | Linq