Thursday, February 25, 2010 4:56 PM
LINQ as we all know provides intrinsic data querying capabilities to the framework languages supporting LINQ. Going forward its an obvious way to code clean, and with growing number of LINQ providers (LINQ to SQL, LINQ to Entities, LINQ to XML, LINQ for Maps, and not to forget DryadLinq and pLinq for us Cloudy folks’ Parallel Computing needs, and so on) it looks to be the de facto standard for querying within dotnet framework languages.
Let us get acquainted to LINQ by taking a close look at the beauty and simplicity of LINQ, instead of getting into technical nitty-gritty’s.
We can start off with simple scenarios where we inherently use loops and replace the codes with LINQ equivalents. Going forward we can include complex looping operations in growing order of complexities.
To kick off let’s look at some interesting Linq alternatives to de-rigueur C# code:
//Initialize an array with 10 as default value
//Loop
int[] iArr = new int[11];
for(int i = 0; i < 11; i++)
{
iArr[i] = 10;
}
//LINQ
int[] iArr = Enumerable.Repeat(10, 11).ToArray();
//Fill an array with 1 to 100
//Loop
int[] iArr = new int[100];
for(int i = 1; i < 101; i++)
{
iArr[i-1] = i;
}
//LINQ
int[] iArr = Enumerable.Range(0, 100).ToArray();
//Fill an array with 100, 150, 200, 250, ..... upto 100 Terms
//Loop
int[] iArr = new int[100];
for (int i = 0; i < 100; i++)
{
if (i != 0)
{
iArr[i] = iArr[i-1]+50;
}
else
{
iArr[i] = 100;
}
}
//LINQ
int[] c = Enumerable.Range(0, 100).Select(i => 100 + 50 * i).ToArray();
Feel free to provide valuable feedback about the kind of content you expect in this initiative.
PS: Thanks to Nathan Kelly, this post stands corrected.