Introduction to LINQ, Extension methods and Lambda Expressions


LINQ

LINQ is shorthand for Language Integragted Query. If you have previous experience in SQL, you are going to have a head start in LINQ. Today a big challenge in  programming technology is to reduce the complexity of accessing and integrating information that is not defined using OO technology.

LINQ defines a set of  standard query operators that allow traversal, filter, and projection operations to be expressed directly in any .NET-based language

The standard query operators allow queries to be applied to any IEnumerable<T>-based information source(e.g arrays and collections). In the following example we'll begin with a simple C# program that uses the standard query operators to process the contents of an array:

namespace ConsoleApplication1
{ 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            //Declare a string array 
            string[] names = { "Ashish", "James", "Albert"}; 
              var query = from s in names                                                                 
              where s.ToLower().StartsWith("a")                                        
              orderby s 
              select s; 
            //Following will output Ashish,Albert as they startrs with "a" 
            foreach (string item in query) 
                Console.WriteLine(item); 
            Console.ReadLine(); 
        } 
    }
}

The variable query is initialized with a query expression. A query expression operates on one or more information sources by applying one or more query operators from either the standard query operators or domain-specific operators. This expression uses three of the standard query operators: Where, OrderBy, and Select.


Lets go through the above Query expression one by one.

              query =from s in names                                                               

              where s.ToLower().StartsWith("a")                                        

              orderby s

              select s; 

We declare the variable query and request that its type be inferred for us by using the "var" keyword

Next is from statement that always starts a query. It takes a collection of some kind after the "in" keyword and makes what is to the left of the "in" keyword refer to a single element of the collection

Following this is another new keyword: where This introduces a filter, allowing us to pick only some of the objects from the Orders collection

OrderBy works usait like its SQL counterpart to sort the result.

The final new keyword is select.It states the result we want to appear in query.

IEnumerable<string> query = names 
                            .Where(s => s.StartsWith("a")) 
                            .OrderBy(s => s)
                            .Select(s => s.ToUpper());

We can express the above query in this form as well.This form of query is called a method-based query which uses lambda expressions and extension methods Lets go through them one by one.. The arguments to the Where, OrderBy, and Select operators are called lambda expressions.

Lambda Expression

A lambda expression is an anonymous function that can contain expressions and statements, and can be used inplace of  delegates and anonymous methods.


A lambda expression normally takes the form of arguments => expression, the expression is always preceded by the => token.  The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block.

If you want to have a lambda expression with more than one argument you must enclose the arguments in parentheses delimited by a comma.


The lambda expression
x => x * x is read "x goes to x times x."

 

Following adds the two integers using lambda expression.

(int x,int y) => x + y

Extension methods

Extension methods make it possible to extend existing types and constructed types with additional methods. Extension methods are static methods that can be invoked using instance method syntax.

We declare extension methods by using the this keyword on the first parameter of the method.We can declare extension methods only in an static class and the extension method itself should be static.

In the following example we will be extending the string class by using the extension method to see if the name is "ashish".

static class ExttensionMethodClass

    {        

        public static bool CheckName(this string Name)

        { 
            if (Name == "ashish")

            {

                return true;

            }

            else

            {

                return false;

            }  

        }  

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            //we are going to add an extension method to check the name is ashish.We will call our class ExttensionMethodClass

            string name = "ashish";

            Console.WriteLine(name.CheckName());

            Console.ReadLine();

        }

    }

Up Next
    Ebook Download
    View all
    Learn
    View all