Saturday, October 31, 2009

LINQ kick start with basic samples

Hi guys,

For some developers LINQ is still new, as they still working on 2.0. So for those who are bingers to the LINQ, I would like to share few stuff. Although whatever I am writing over here is available in the msdn, I will try to present that all in some different flavor.

Mostly in this article I have covered small but helpful features provided with LINQ.
Generally, using LINQ we are supposed to play with three type of collection. i.e.

  • LINQ: Language Integrated Query for in memory objects (LINQ to Objects)
  • DLINQ: Language Integrated Query for databases (LINQ to ADO NET)
  • XLINQ: Language Integrated Query for XML (LINQ to XML)
Over here for showing examples, I have used only object collection. So everyone can try out these samples within few minutes.

1) So, let’s start with simplest example of LINQ.
int[] numbers = { 4, 5, 3, 1, 9, 8, 6, 7, 2, 0 };
// other operators that can be used are &&, ==,> etc…
var firstFive = from n in numbers where n < 5 select n; //This will filter the collection and if you print firstFive then it would show 4, 3, 1, 2, 0.

2) We can even use two collection to filter the objects for e.g.
string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
var lowNums = from n in numbers where n < 5 select digits[n]; // This will filter the collection and if you print lowNums then it would show four, three, one, two, zero.

3) We can also perform some arithmetic operation. For e.g.
If we want to add 1 in all digit of numbers collection before we use it to render. We can do that using + sign. i.e.
var numsPlusOne = from n in numbers select n + 1; // As a result if we print numsPlusOne collection it would print like 5, 6, 4 and so on. Similarly we can use other arithmetic signs -, * and /

4) It is also possible with LINQ to use ToLower and ToUpper for e.g.
string[] words = { "aPPLE", "BlUeBeRrY", "cHeRry" };
var LowerWords = from w in words select w.ToLower(); // As a result if we print LowerWords it would print like apple, blueberry, cherry.

5) Taking particular items or skipping them would be easy with LINQ for e.g.
var first3Numbers = numbers.Take(3); //will print 4, 5, 3
var allButFirst7Numbers = numbers.Skip(7); //will print 7, 2, 0

6) Even taking particular items with condition or skipping them would be possible with LINQ for e.g.
var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6); //will result as first four digit 4, 5, 3, 1.
var firstNumbersLessThan6 = numbers.SkipWhile(n => n < 6); //will result as last six digit 9, 8, 6, 7, 2, 0.

7) We can also use orderby with LINQ for e.g
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords = from w in words orderby w select w; //this will result as apple, blueberry, cherry.

8) We can also reverse the collection using LINQ for e.g
var firstFiveReverse = (from n in numbers where n < 5 select n).Reverse(); //will result as 0, 2, 1, 3, 4.

9) It is also possible to use distinct or group by with LINQ for e.g.
int[] Factors = { 2, 2, 3, 5, 5 };
var uniqueFactors = Factors.Distinct(); will print 2, 3, 5.

10) We can use union, intersect and except with LINQ for e.g.
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
var uniqueNumbers = numbersA.Union(numbersB); // this will print all unique numbers from both the collection.
IEnumerable aOnlyNumbers = numbersA.Except(numbersB);// this will print all numberA’s digit except numbersB’s digit.
var commonNumbers = numbersA.Intersect(numbersB); //this will print common numbers of both the collection.

11) The conversion of collection object to list, array or dictionary is possible using LINQ for e.g.
string[] words = { "cherry", "apple", "blueberry" };
var sortedWords = from w in words orderby w select w;
var wordList = sortedWords.ToList(); // here we have converted string array to list.

12) You can even find out particular type of item from the object collection for e.g.
object[] numbers = { null, 1.0, "two", 3, 4.0f, 5, "six", 7.0 };
var doubles = numbers.OfType(); //will print 1.0, 7.0

13) One can search first element or element at any particular position.
int firstNumOrDefault = numbers.First(); //will print 4.
int fourthLowNum = (from n in numbers where n < 5 select n).ElementAt(3); //will print 1.

14) We can use count, min, max, sum, average, aggregate with LINQ.
var uniqueFactorsCount = Factors.Distinct().Count(); //will print 3.
Same way of Count() we can use any of the above function.

15) We can also use concat functionality with LINQ.
var allNumbers = numbersA.Concat(numbersB); //this will print 0, 2, 4, 5, 6, 8, 9, 1, 3, 5, 7, 8.

I feel once we understand the capability and usage of LINQ then we will start implementing it in our day to day programming. So this is just an effort to give some basic idea about what we can do with LINQ. I feel this is at least enough to start with.