Join Us On Facebook

Please Wait 10 Seconds...!!!Skip

Saturday, 4 May 2013

LINQ -Knowledge & Practice-part 2

hey guys! you have read my previous post 'LINQ-Knowledge & practice' , which is focused about basic knowledge about LINQ,but you know without practical and practice you can't understand anything in programming.so I will try to give you ability to make a good sense about LINQ.

Lets take an example, In which you have to fetch even number from given set of numbers, so If you don't know LINQ then you will go to looping to traverse numbers one by one,then you can get your result.This is very lengthy process and also produce poor performance.

Now try the above example with LINQ-

class EvenNumber
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3, 6, 7, 8,9,10,11,12,13,14,15,16,17,18,19,20 };
            // Query expression for linq.
            var elements = from element in array 
                           orderby element 
                           where (element%2)==0
                           select element;

//all the even numbers is in 'elements'

            // Enumerate.
            foreach (var element in elements)
            {
                Console.Write(element);
                Console.Write(' ');
            }
            Console.WriteLine();
        }
    } 

when you run this program ,you will found this result-

2 6 8 10 12 14 16 18 20
so you can see you get even number to just write couples of line without traversing numbers one by one.
when you reading above code then your are aware about all codes such as foreach,var keyword etc, but you are confused in Query Expression section, so lets start to understand how to write LINQ Query Expression.


 var elements =                                          //query variable 
                           from element in array      //This is required
                           orderby element             //This is optional 
                           where (element%2)==0   //This is optional 
                           select element;                 //must end with select or group


This is just starting of LINQ. there are many concept which is most useful to write LINQ query, so lets discuss about some of these ,which is most important-

1.Anonymous type:-
                              Anonymous type is the type that is created anonymously. Anonymous type is a class that is created automatically by compiler in somewhere you can’t see directly while you are declaring the structure of that class. Confused? Let me show you one example.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LINQ
{
    class Program
    {
        static void Main(string[] args)
        {           
            Employee employee = new Employee { ID = 1, Name = "Anoop", city = "Varanasi" };
            Console.WriteLine("Name: {0} and city: {1}", employee.Name, employee.city);
            Console.ReadLine();
        }
    }

    //employee class
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string city { get; set; }
    }
}

This is normal way  of creating a class and initializing the instance that we have been doing this for couples of years.Till here we are not using Anonymous type.



The first thing that you need to do is that remove the class. (C# compiler will create the anonymous class based on what you initialize with.) Secondly, we have to change employee variable to implicitly-typed local variable by replacing “Employee” with “var”. Because we have removed Employee class from our code so that we won’t know about the type. That’s why the variable “employee ” should be declared as a implicitly-typed local variable. Then, we will remove “Employee ” after “new” keyword.

So, our final code will be like that below-


namespace LINQ
{


class Program
        {
            static void Main(string[] args)
            {
                var employee = new
                {
                    ID = 1,
                    Name = "Anoop",
                    city = "Varanasi"
                };

                Console.WriteLine("Name: {0} and city: {1}", employee.Name, employee.city);
                Console.ReadLine();
            }
        }
}


2. Object Initializers :-
                                     Object initializers lets you assign values to the properties of an objects at the time
of creating the object. Normally in .NET 1.1 and 2.0, we define the class with properties, then create the instance, and then define the values for properties either in constructor or in the function which is using the object. Here, in C# 3.0 we can define the values at the time of creation itself.

Lets take an example-
we have to make class of Milk with two properties- Name and Price


public class Milk
{
public string Name { get; set; }
public double Price { get; set; }
}

                                        
Now, in C# 2.0, we would have to write a piece of code like this to create a Milk instance and set its properties:

        Milk milk = new Milk();
                milk.Name = "Toned Milk";
                milk.Price = 15.50;


It's just fine really, but with C# 3.0, it can be done a bit more cleanly, thanks to the new object initializer syntax:
 Milk milk = new Milk { Name = "Toned milk", Price = 15.50 };


3.Collection Initializers:-
                                       Collection initializers use object initializers to initialize their object collection. By using a collection initializer, we do not have to initialize objects by having multiple calls.Just like C# 3.0 offers a new way of initializing objects, a new syntax for initializing a list with a specific set of items added to it, has been included. Lets take example of 'Milk' class of above example.

If we wanted to create a list to contain a types of milk, we would have to do something like this with C# 2.0:



               Milk milk;
                List<Milk> milklist = new List<Milk>();

                milk = new Milk();
                milk.Name = "Toned Milk";
                milk.Price = 15.50;
                milklist.Add(milk);

                milk = new Milk();
                milk.Name = "full cream";
                milk.Price = 20;
                milklist.Add(milk);

Using object initializers, we could do it a bit shorter:


         List<Milk> milklist= new List<Milk>();
                cars.Add(new Milk { Name = "Toned Milk", Price = 15.50 });
                cars.Add(new Milk { Name = "full cream", Price = 20 });

However, it can be even simpler, when combined with collection initializers:


List<Milk> milklist = new List<Milk> 
                {
                    new Milk {  Name = "Toned Milk", Price = 15.50 },
                    new Milk { Name = "full cream", Price = 20}
                };


4.Lambda Expressions:-
                                         Lambda expressions are similar to Anonymous Functions introduced in C# 2.0, except that lambda expressions are more concise and more flexible. All lambda expressions use the lambda operator =>, which is read as “goes to”. Lambda expressions use special syntax. They allow functions to be used as data such as variables or fields. The lambda expression syntax uses the => operator. This separates the parameters and statement body of the anonymous function.
Lets EvenNumber class(given above) converted in lamda expression form-


 class EvenNumber
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3, 6, 7, 8,9,10,11,12,13,14,15,16,17,18,19,20 }; 
            //Lamda expression is used below
            var evenNumber= array.Where(n => n % 2 == 0);
           //all the even numbers is in 'elements'           
            foreach (var element in evenNumber)
            {
                Console.Write(element);
                Console.Write(' ');
            }
            Console.WriteLine();
        }
    } 



when you run this program ,you will found this result-

2 6 8 10 12 14 16 18 20




Now I am giving you a complete example to understand LINQ with including of all above concept.
Taking the example of milk class, In which we created milk list and finding the milk has price less than or equal to 15.


namespace LINQ
{
    public class Milk
    {
        public string name;
        public string totalFat;
        public string cholesterol;
        public string totalCarbohydrates;
        public string protein;
        public double price;
    }

    class LinqExample
    {
        static void Main(string[] args)
        {
            List<Milk> milkList = new List<Milk>
        {
                            new Milk
                            {
                            name="Toned",
                            totalFat="35g",
                            cholesterol="90mg",
                            totalCarbohydrates="35g",
                            protein="4g",
                            price=15
                            },
                            new Milk
                            {
                            name="Double Toned",
                            totalFat="86g",
                            cholesterol="55mg",
                            totalCarbohydrates="96g",
                            protein="4g", price=13.50
                            },
                            new Milk
                            {
                            name="Full Cream",
                            totalFat="03g",
                            cholesterol="08mg",
                            totalCarbohydrates="04g", protein="6g",
                            price=20
                            }
        };

            var MilkLessPrice =
                                        from milk in milkList
                                        where milk.price <= 15
                                        select new
                                        {
                                            Name = milk.name,
                                            Price = milk.price
                                        };
            Console.WriteLine("Milk with price less than 15:");
            foreach (var milkitem in MilkLessPrice)
            {
                Console.WriteLine("{0} is {1}", milkitem.Name,
                milkitem.Price);
            }
        }
    }
}


Enjoy this post , and will meet soon for next post ,which is focuses to topic-"LINQ to Object'
happy programming !!




1 comment: