LINQ: where Asp.net shines! 1


LINQ (Language INtegrated Query) is one of the features you will like in Asp.net. It is not easy to master but once you get used to it, you will find that it is one of the powerful language to manipulate XML documents, to query relational databases, to manipulate collections of objects in memory, etc.

What do we need to know for mastering LINQ?

Different notions and concepts are involved in LINQ language:
1. Delegate and generic delegate;
2. Anonymous methods;
3. Lambda Expression;
4. Extension Method;
Once we understand those concepts, working with LINQ becomes a charm, that is the reason before going into details about LINQ, I start by an overview of these fundamental notions.

Delagate, Anonymous Method, Lambda Expression

To define delegate, I use the text from Andrew Troelsen (2012, p.359)

Under the .NET platform, the delegate type is the preferred means of defining and responding to callbacks within applications. Essentially, the .NET delegate type is a type-safe object that “points to” a method or a list of methods that can be invoked at a later time. Unlike a traditional C++ function pointer, however, .NET delegates are classes that have built-in support for multicasting and asynchronous method invocation.
Anonymous method is defined as a block of code without name. The key “delegate” is used to define that block, and Lambda Expression is a compact form of the anonymous method.
Asp.net has built in delegates, Action<T> is built in delegate which does not return a value; Func<T,TResult> is a built-in delegate that receives type T as parameter and return type TResult.
The follow code illustrates use of delegate,anonymous method, Lambda Expression, Action and Func

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegatesApp
{
    class Program
    {
        public delegate int MyDelegateOp(int x, int y);
        static void Main(string[] args)
        {
            Console.WriteLine("App Starting ...");
            //Instanciate delegate by named methods
            //=========================================
            MyDelegateOp myDelegateOp = new MyDelegateOp(InstantiateDelageteByNamedMethod);
            Console.WriteLine("10 + 10: {0}", myDelegateOp(10,10));
            //Instanciate delegate by anonymous method
            //================================================
            MyDelegateOp divideOperation = delegate(int a, int b)
            {
                Console.WriteLine("Anonymous method");
                return a/b;
            };
            Console.WriteLine("10 / 5 {0} ", divideOperation(10, 5));
            //Lambda expression==============================
            MyDelegateOp moduloOperation = (a, b) => a % b;
            Console.WriteLine("10 % 3 {0} ", moduloOperation(10, 3));
            //Action=============
            Action<string> message=s=>
            {
                Console.WriteLine("In Action "+s);
            };
            message("Cool C#");
            //Funct===================
            Func<int,int,int> MyFunc=(x,y)=>x*y;
            Console.WriteLine("MyFunc {0}",MyFunc(10, 5));
            Console.WriteLine("Press Any Key to Exit ...");
            Console.ReadLine();
        }
        private static int InstantiateDelageteByNamedMethod(int x, int y)
        {
            return (x + y);
        }
    }
}

In this code, a dalegate has been defined (line 10) “MyDelegateOp” that takes two integer parameters x, y and returns an integer.
There are different ways to instantiate our delegate: firstly, a named method “InstanciateDelageteByNamedMethod” has been used (line 16), this method has same signature with our delegate; secondly, the delegate method has been instantiated by anonymous method (line 20), thirdly lambda expression has been used (line 27).You can see how lambda expression simplifies the code. No need to go into details regarding Lambda Expression there are more information at this web site.
Asp.net built-in delegates, Action and Func, have been used at line 30 and line 36, for further examples, you can always go to this web page

Extension Methods

An Extension Method lets us add a new method to an existing class without modifying this class. The following code illustrates how a class StringExtension has been used to extend the String class (System.String)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Namespace where the method is defined
namespace ExtensionMethods
{
    static class StringExtension
    {
        static public bool CheckLength(this string value)
        {
            return value.Length > 10;
        }
    }
}

The extension class has to be static and the extension method has to be static as well. The key word this has to be part of the method ( see line 11 in code).
The following code use the above code to check the string length (line 17).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Bring the namespace where the extension is defined
using ExtensionMethods;
//==================================================
namespace ExtensionMethodApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Starting App ...");
            string myStringExtension = "Linq makes Asp.net powerful!";
            bool isCorrect = myStringExtension.CheckLength();
            if (isCorrect)
                Console.WriteLine("Got It!");
            else
                Console.WriteLine("Length No Correct");
            Console.WriteLine("Press Any Key to Exit...");
            Console.ReadKey();
        }
    }
}

For more information on extension methods, have a look at this web site

For completeness, I would like to suggest you to have look at these web sites regarding IEnumerable and IQueryable Interfaces because they are commonly used in LINQ language (cornerstone of LINQ, I would say!)

Conclusion

In this post, the concepts and notions behind LINQ have been highlighted. The LINQ makes life easier for Asp.net developers as far as productivity is concerned. Practical examples to come in next posts. Stay tuned.


Leave a comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

One thought on “LINQ: where Asp.net shines!