Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Saturday, 3 November 2012

DelayLoading is true/false(default) in Linq to Sql?

Yes, linq to sql uses lazy loading/delayloading --->give good performance by default with the help of

DelayLoading =False(default)--->along with the Column name

like
 ProductName  Delay Loaded=false








then ProductName Delay Loaded=true------> this ProductName is not loaded.

Note : If we set Delay Loaded =true for Primay key column ------>Even also which will loaded.




Thursday, 1 November 2012

Lamda Expressions simplifies the coding?


Lamda Expressions simplifies the coding?
Yes, Lamda expression simplifies the coding …
Lamda expression return type should by a delegate type.
Delegate =from n in lamda expression.

CASE -I
Expression<Func<int, int, int>> expression1 = (x) =>x * x;
int value1 = expression1.Compile().Invoke(4, 4);



treates as Expression type

public sealed class Expression<TDelegate> : LambdaExpression
{

      public  TDelegate  Compile();
}

so 

expression.Complie() -----> returns also TDelegate

incase of invoke based on type of delegate which take paramters

like

int value=expression1.complie().invoke(4);

               or

Fun<int,int> expr=expression1.complie();
int val=expr.invoke(4);
console.write(val);

Because of
Expression1.Compile()-à consider as delegate
so invoke() method.

CASE-II

Func<int, int, int> expression2 = (a, b) => a * b;
int value2 = expression2.Invoke(41, 424);



treates as Delegate type

we know that delegate has Invoke method of

Console.WriteLine(value1);---17384
           
Console.WriteLine(value2);---17384

HERE output same

System.Linq.Expressionsà contains

public abstract class Expression
{
protected Expression(ExpressionType nodeType, Type type);
public ExpressionType NodeType { get; }
public Type Type { get; }
BindaryExpression,
UnaryExpression,
 MethodCallExpression……ect
}        

ExpressionType: Add,Multiple,Substract..ect
Type: int,string,…..ect.
For initialize the Expression tree.

ExpressionàBody and Paramters

Body----implementsà Binary Expression/Uniary Expression/Constant Expression..ect
Based on the type Body expression parameters will changes.


As well based on Binary operation NodeType also changes.

NodeType: Add, Multiple,Subtract,Devide…ect

So all the properties are belogs to BindaryExpression.

Ex:

How to build expression tree?

Expression tree= Body+Paramters.

Demo 1: building BinaryExpression 

Parametersà

  ParameterExpression parameter1 = Expression.Parameter(typeof(int), "x");
Body------à
  BinaryExpression multiply = Expression.Multiply(parameter1, parameter1);
  Expression<Func<int, int>> square = Expression.Lambda<Func<int, int>>(
             multiply, parameter1);

Expression static class defines : Expression<TDelegate> Lambda<TDelegate>(


Func<int, int> lambda = square.Compile();
Console.WriteLine(lambda(4));------> 16

// return type should be Apporiate delegate type          // Fun<int,int>

Or

int lamda=square.Compile().Invoke(4);----->16
Console.WriteLine(lambda);

so

ParameterExpression parameter1 = Expression.Parameter(typeof(int), "x");
BinaryExpression multiply = Expression.Multiply(parameter1, parameter1);
Expression<Func<int, int>> square = Expression.Lambda<Func<int, int>>(multiply, parameter1);
Func<int,int> lamda= square.Compile();
Console.WriteLine(lamda(4));




this is simplified like 

Func<int, int, int> expression2 = (a, b) => a * b;
int value22 = expression2.Invoke(41, 424);
Console.WriteLine(value22);



Here square is a Delegate of type which takes 2 parameters.so return type also a delegate which takes same structure.

public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters);
public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters);

advantages:

we can reduce the no'f method to declaring.

based on the signature of method which will execute.

Demo 2: UnaryExpression




references:
http://weblogs.asp.net/dixin/archive/2009/11/29/understanding-csharp-3-0-features-6-lambda-expression.aspx

http://www.dotnetfunda.com/articles/article1956-func-and-action-delegates.aspx

Monday, 22 October 2012

How to use Projection Operatiors in LINQ?


we have many projection operators in linq like: Select(),where()....are Extension methods takes delegates as

input parameters


    var numbers = new[] { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };
var values= numbers.Where((n, index) => (index % 2) != 0).ToList();
foreach(int item in values)
{
      Console.WriteLine(item.Tostring())
}
Here: numbers.Where(Fun<int,bool>,predicate)
based on source(numbers).so delegate points to integers.
another example is
  var names = new[] { "app", "balu", "charan", "dhanush" };

IEnumerable<string> stringvalues = names.Where(s => s.Contains("charan")).ToList();
            foreach (string item in stringvalues)
            {
                Console.WriteLine(item.ToString());
            }
Here: names.Where(Fun<string,bool>,predicate);
As well in case of custom types like Students
List<Students> val = new List<Students>();
val.Add(new Students { Name = "aanand", Age = 22,City="Hyd" });
val.Add(new Students { Name = "balu", Age = 24,City="Pune" });
val.Add(new Students { Name = "charan", Age = 19,City="Bangalore" });
val.Add(new Students { Name = "dinesh", Age = 19, City="Hyd"});
or
// List<Students> val = new List<Students>(IEnumerable ier)
IEnumerable<Students> t = val.Where((Students, s1) => (Students.City == "Hyd"));----2nd predicate

--àt.Where(Fun<Student,int,bool>);

IEnumerable<Students> t = val.Where(Students => (Students.City == "Hyd"));
       --- 1st predicate
--àt.Where(Fun<Student,bool>,predicate);
And
1st predicate
(Students.City == "Hyd")-àreturn True/False.


Early loading/eagar loading:
index % 2 != 0
true
index % 2 != 0
false
index % 2 != 0
true
index % 2 != 0
false
index % 2 != 0
true

if students belongs to Hyd returns true other wise false.
2nd predicate
Val.Where((students,s1)=>(Students.City==”Hyd”));
if students belongs to Hyd returns true other wise false.
   foreach (Students item in t)
   {
       Console.WriteLine(item.Name+" "  +item.Age+"   "+item.City);
   }
Output:
1,3,8,21,55---intarray
Charan-----stringarray
Anand 22 Hyd
Dinesh 19 Hyd


s.Contains("charan")
false
s.Contains("charan")
false
s.Contains("charan")
true
s.Contains("charan")
false
s.Contains("charan")
The name 's' does not exist in the current context

above 2 are eagar/early loading.

Select Predicate:
List<Students> val = new List<Students>();
            val.Add(new Students { Name = "aanand", Age = 22, City = "Hyd" });
            val.Add(new Students { Name = "balu", Age = 24, City = "Pune" });
            val.Add(new Students { Name = "charan", Age = 19, City = "Bangalore" });
            val.Add(new Students { Name = "dinesh", Age = 19, City = "Hyd" });
   
 IEnumerable<Students> stuvalues = val.Select(r => r);



            foreach (Students item in stuvalues)
            {
                Console.WriteLine(item.City);
            }
2nd predicate:
IEnumerable<string> stuvalues = val.Select(r => r.City);

or
IEnumerable<string> stuvalues = val.Select<Students, string>(r => r.City);
    foreach (string item in stuvalues)
   {
                Console.WriteLine(item.City);
   }

but

Lazy loading/deffered loading

Students.City=="Hyd"
false
Students.City=="Hyd"
True



Both perdicates: where and select

IEnumerable<Students> stuvalues = val.Where((Students, s1) => (Students.City == "Hyd")).Select(r => r);

or


IEnumerable<Students> stuvalues = val.Where((Students, s1) => (Students.City == "Hyd"));//.Select(r => r);

            foreach (Students item in stuvalues)
            {
                Console.WriteLine(item.City);
            }
IEnumerable<string> stuvalues = val.Where((Students, s1) => (Students.City == "Hyd")).Select(r => r.City);
            foreach (string item in stuvalues)
            {
                Console.WriteLine(item);
            }
Note: projection operator can be where/select.but the return type is should math
both the sites

we can know the return type of Linq query while showing

like

before writing select projection in linq query




after writing select projection in linq query

Friday, 19 October 2012

What is lazy/deffer loading and eagar loading?



lazy loading: requirement is matched/reached then only query reaches the data source.and coming to    eager loading –all the data is feach from the datasource.


yeild is a keyword which is used to returns collection of  Elements ----of  typeà IEnumerable<T>  elements. 

Yield by default returns IEnumerable which is generated by complier.
Yield returns elements in type safe manner.
yield makes demand-driven programming.means our requirement/condition  is satisfied then  it will return elements.  Which is also called as lazy loading. Which is benefit. Why because instead of  loading all the elements form  collection or datasource  to in-memory. So linq makes memory utilization.
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int j;
            IEnumerable<int> k=Gettwo();
            IEnumerator<int> s = k.GetEnumerator();
            while (s.MoveNext())
            {
                 j = s.Current;
                Console.WriteLine(j.ToString());
            }          
            Console.ReadKey();
       
        }
        public static IEnumerable<int> Gettwo()
        {
            for (int i = 0; i < 5; i++)
            {
                if (i % 2 == 0)
                {
                    yield return i;  // yield return type is IEnumerable<T>
                }

            }
       
        }
    }
}

 lazy(deffered) loading// also called as demand-driven programming(based on requirement is reached)

// if our requirement is reached the our query touch the datasource. this is done through IEnumerable<T> interface.

Based on the select query requirement

Return type of 

IEnumerable<T> will be changes
Ex: select {n=>n.ID}----------------Eid
Select{ n=> n.Name}--------Ename;
Select { n=>n.Dept}----Department……….ect.

As well as
Based on select query
IEnumerable<T> will changes
Like
IEnumerable<string> slist = student1.Where(n => n.Name == "charan").Select(n=>n.Name);
IEnumerable<int> slist = student1.Where(n => n.Name == "charan").Select(n=>n.Age);
IEnumerable<Students> slist = student1.Where(n => n.Name == "charan").Select(n=>n);

As well

Deffered Execution[lazy loading]

// lazy(deffered) loading// also called as demand-driven programming(based on requirement is reached)
if our requirement is reached the our query touch the datasource. this is done through IEnumerable<T> interface.

List<Students> student1 = new List<Students>();
student1.Add(new Students { Name = "anand", Age = 20 });
student1.Add(new Students { Name = "balu", Age = 21 });
student1.Add(new Students { Name = "charan", Age = 19 });

IEnumerable<int> slist = student1.Where(n => n.Name == "charan").Select(n=>n.Age);

student1.Add(new Students { Name = "charan", Age = 47 });
            int i = 1;
            foreach (int item in slist)
            {                               
                Console.WriteLine(item + "\n");
                Console.WriteLine("Total Iteration is:     " +i.ToString());
                i++;
            }
            Console.ReadKey();

Output:

four students are available but two students(iterations) only meet our requirement. so query also executed 2 times only.

Total iteration are 2 .

Incase of dubugging 3 step and 4 step of F11 only the n.Age will be featched from the datasource==ènow here slist.

Remaining means à 1st 2nd times foreach is not be executed.
So finally I says

This is called deffered/on demand/demand-drive programming……

On-demand[ our requirement is name=”charan” ] satisfies then only foreach will executes.


Here students are 4 but iteration is 2 times only.

Eagerloading:

    List<Students> student1 = new List<Students>();
            student1.Add(new Students { Name = "anand", Age = 20 });
            student1.Add(new Students { Name = "balu", Age = 21 });
            student1.Add(new Students { Name = "charan", Age = 19 });

  IEnumerable<int> slist = student1.Where(n => n.Name == "charan").Select(n=>n.Age);

            //int j = slist.Count<int>(); //----here count is 1

            student1.Add(new Students { Name = "charan", Age = 47 });

            int j = slist.Count<int>();   //----here count is 2

            int i = 1;
            foreach (int item in slist)
            {                               
                Console.WriteLine(item + "\n");
                Console.WriteLine("Total Iteration is:     " +i.ToString());
                i++;
            }

            Console.Write(j.ToString());

So count is done once all the students are loaded.// or slist is prepared.

Default in Linq to Sql is Differed/lazy loading


using (wcfDataContext b=new wcfDataContext())
            {
               
                  
 IQueryable<emp> data = from n in b.emps where n.ename == "sai11" select n;

this is executed as differed loading/ lazy loading(not early loading.

{SELECT [t0].[eid], [t0].[ename], [t0].[eloc], [t0].[deptr], [t0].[uploadstatus]
FROM [dbo].[emp] AS [t0]
WHERE [t0].[ename] = @p0



before control moves to foreach stament this exection is done so count is 3 only

in database with the name : Sai11 availble records are 3 only.

                foreach (emp item in data)
                {
                    Console.WriteLine(item.eloc);
                }
                Console.ReadKey();
            
            }
Here is: