As a developer, most my major tasks were dealing with data;
so it is important to found out what is the most efficient object that could be
used with handling a collection of data and objects.
In .NET 2003, Microsoft give us the System.Collections
namespace; which enable you to store and manipulate a collection of objects (it
could be various types of objects) inside one collection; such as the ArrayList
class. As you can see in listing 1, we have saved various object types inside
one ArrayList collection, and that gives us flexibility in dealing with various
data types.
Listing 1: .NET 1.0 ArrayList Sample:
Dim arr As New ArrayList()
arr.Add("Hello World!")
arr.Add(10)
arr.Add(True)
Unfortunately, this flexibility could give you a worst
result if you use it in wrong way; it could slow down the performance with
casting between types (Boxing & UnBoxing), also it could give you a runt
time error.
To overcome this problem, .NET framework 2.0 give us a new
feature which is System.Collections.Generic
namespace; it allow you to create a collection of specific type of object, see
listing 2.
Listing 2 : Framework 2.0 (Generic)
Dim arr2 As New List(Of String)
arr2(0) = "Abdulla"
arr2(1) = "Oday"
This time, the compiler will know that arr2 is a collection
of string, so there is no need for casting any more which will increase the
performance, also that will avoid Boxing-UnBoxing mechanism, in addition, there
will be no run time error, because you have specified that arr2 is a collection
of specific type, so you can catch and handle these possible errors when you build
the project before you running it, we can say Generics are a strongly type
object (safe type object).
The previous sample was too simple, but in real live code,
generics are widely used in creating a collection of class.
Ok let's back to our main subject, why this brief
introduction? What I am trying to tell you that LINQ comes to serve these
various types of objects, specifically LINQ to object, you can say LINQ is the
high level of dealing with objects and data.
As I said before, this is a LINQ to Object article, so all
my samples will be only for LINQ to object.
In the next section, we will see how LINQ could manipulate a
collection of objects in few lines of code.