Saturday, January 30, 2010

LINQ queries for integer and string array

In this post i will show some basic queries which we can make on the array in .Net environment.

First of all we will see LINQ query for integer array.

 

   1:  int[] intArray = { 1, 5, 7, 15, 19, 20 };
   2:  var query = from i in intArray
   3:              where i % 5 == 0
   4:              select i;

 

In above example i had defined an integer array as intArray. above LINQ query will select all the integer value which can be divisible with 5.

So its output will be {5, 15, 20}

This was basically searching functionality. Now if you need to sum all the values within array, you can achieve it with below LINQ statement

   1:  int sum = intArray.Sum();

And it will give you sum of all the array

For average the array in LINQ you need to write

   1:  int avg = intArray.Average();

 

Now lets take another example of a string array.

   1:  string[] strArray = {"red", "blue","green", "black", "yellow" };
   2:  var query = from s in strArray
   3:              where s.StartsWith("b")
   4:              select s;

 

Now in this example i have an array of string containing various color name. Above LINQ query will select all the name that starting with be.

So its output will be {“blue”, “black”}

LINQ provide developers a great way to use logic that we can build in C# and LINQ will handle it.

There are much more functionality LINQ provides like concate, reverse, first, last, etc.