AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1848&pId=-1
LINQ the Bridge between the world of Objects & the world of Data
page
by Abdulla Hussein AbdelHaq
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 29742/ 65

Introduction

This article will not make you an expert in LINQ, you can find thousands of articles that talk about LINQ in details, but you can say that this article is like developer to developer tech-talk.

I will try as "a developer" to illustrate what useful things that I found in LINQ, and makes me surprised how it could reduce my line of code using new rich query language that become a part of the .NET platform.

Through the article, we will talk about LINQ to Object, and we will make a comparison between regular code and LINQ code.

 

What is LINQ?

Language-Integrated Query (LINQ) as MSDN definition is a groundbreaking innovation in Visual Studio 2008 and the .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data.

 Definitely you have faced some kind of tasks that required from you to deal with various data source such as SQL Database, XML document or Strongly typed of objects, and you have to do some operations on it, such as fetching data, saving data … etc, in that case you need to learn different query language or different syntax for each data source type and writing couple of complex statements, fighting with crazy loops and sets of objects and finding the most efficient object that match your requirements, and so on.

 LINQ makes these things get to be easier to deal with, and provide us a new rich query language that become a part of .NET platform.  You can say SQL statements are become part of the C# and VB.net code, you do not need to use SQLCommand or any other ADO.NET classes to write queries; you can simply use these SQL statement (keywords and familiar operators) within your code.

Why LINQ?

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.

LINQ to Object

 

To get start working with LINQ, we need to create a class, let's name it "Student" class that contains student name, student grade and student class.

 All next samples will be applied on this class.

Listing 3: Student Class

 
Public Class Student
 
    Private _stName As String = String.Empty
    Private _stGrade As String = String.Empty
    Private _stClass As String = String.Empty
 
    Public Sub New(ByVal nme As StringByVal grd As StringByVal cls As String)
        _stName = nme
        _stGrade = grd
        _stClass = cls
    End Sub
 
    Public Property StudentName() As String
        Get
            Return _stName
        End Get
        Set(ByVal value As String)
            _stName = value
        End Set
    End Property
 
    Public Property StudentGrade() As String
        Get
            Return _stGrade
        End Get
        Set(ByVal value As String)
            _stGrade = value
        End Set
    End Property
 
    Public Property StudentClass() As String
        Get
            Return _stClass
        End Get
        Set(ByVal value As String)
            _stClass = value
        End Set
    End Property
 
End Class

 

Now create an object from that class and add some new elements.

Listing 4.

 
Dim objStudent As New List(Of Student)
 
objStudent.Add(New Student("Abdulla", "92""10"))
objStudent.Add(New Student("Ali", "98""8"))
objStudent.Add(New Student("Rula""95", "10"))
objStudent.Add(New Student("Oday", "95""9"))
objStudent.Add(New Student("Belal""79", "8"))
objStudent.Add(New Student("Sara", "80""8"))

 

Ok, if I ask you to list only student who is name contain "a" character, and his grade more than 90, and he should be in 10 class, Also I want the list to be displayed order by student name descending.

 Finally I want student name to be shown in lowercase mode.

Let's solve this using the regular code, look at Listing 5

Listing 5 Regular Code

 
   Dim obj2 As New List(Of Student)
 
    Dim strName, strGrade, strClass As String
 
 
        For i As Integer = 0 To objStudent.Count - 1
 
            If objStudent.Item(i).StudentName.Contains("a"Then
 
                If objStudent.Item(i).StudentGrade > 90 Then
 
                    If objStudent.Item(i).StudentClass = 10 Then
 
                        strName = objStudent.Item(i).StudentName.ToLower
                        strGrade = objStudent.Item(i).StudentGrade
                        strClass = objStudent.Item(i).StudentClass
 
                        obj2.Add(New Student(strName, strGrade, strClass))
 
                    End If
 
                End If
 
            End If
 
        Next
 
        obj2.Reverse()
 
 
        Me.GridView1.DataSource = obj2
        Me.GridView1.DataBind()

 

Even it was a very simple question, but we have used for loop, 3 nested if condition and we declared new generic list of Student class to collect the filtered students and new three variables too. In addition we used the reverse method to get the new student list to be order in descending way.

Now let's see how LINQ could solve that question only in one line of code using query statements!

Take another Look to the list of student, and make it as you are looking to a table in SQL server.

Listing 6: LINQ code

 

Me.GridView1.DataSource = From st in objStudent _ 
 
Where st.StudentName.Contains("a") _ 
 
AND st.StudentGrade > 90 AND st.StudentClass = 10 _
 
Order By st.StudentName Descending
 
Select st.StudentName.Tolower, st.StudentGrade, st.StudentClass _

 

 
 Me.GridView1.DataBind()

 

SQL statement within VB code, amazing ! Not yet, LINQ return results of type IEnumerable(Of T) (T here will be Student Class), which means that you can bind it directly to any databound control, also LINQ result is a safe type object! I really appreciate that.

 

What about grouping, can I do that with LINQ? Yes you can, look at Listing 7, LINQ groups our student list to be grouped by student class.

Listing 7: LINQ grouping

 
Me.GridView1.DataSource = from st in objStudent _
group st by st.StudentClass
 
 Me.GridView1.DataBind()

 

If you note that in Listing 7, I did not use "select" statement! If you did not specify certain property in select statement, then LINQ will return by default all properties in that object.

We can also skip out some rows and take a certain rows too. Listing 8, LINQ will skip the first 3 rows that returned from the query, and it will take only 10 rows.

Listing 8: LINQ Skip, Take

 

Me.GridView1.DataSource = (From st in objStudent _ 
Where st.StudentName.Contains("a") _ 
AND st.StudentGrade > 90 AND st.StudentClass = 10 _
 Order By st.StudentName Descending
Select st.StudentName.Tolower, st.StudentGrade, st.StudentClass).Skip(3).Take(10);
 
Me.GridView1.DataBind

 

Get Started with LINQ.

There are a lot of operations that you can do with LINQ. It’s a rich query language.

You can find many LINQ articles here in aspalliance, go on and read them. Also I recommend you to have a look at the MSDN 101 LINQ samples; you can find there all LINQ statements with a code sample.

http://msdn.microsoft.com/en-us/vbasic/bb688088.aspx

 

Conclusion

LINQ is a very rich query language, it become a part of the .NET platform. The result of LINQ query is type of IEnumerable(Of T), which means you can bind it directly to a databound control, also LINQ is a safe type object which makes your page more performance and less runt time error.

I tried to illustrate it in simple words; I hope you found it a good point to get start.

 

 


Product Spotlight
Product Spotlight 

©Copyright 1998-2022 ASPAlliance.com  |  Page Processed at 2022-09-24 3:47:14 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search