Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Tuesday, February 10, 2009

LINQ Querry : A Step Ahead Series

LINQ Querry : A Step Ahead Series
History:
The article is related to previous posts :

1. Anonymous Types in LINQ: A Step Ahead Series

2. How to Test Anonymous Type Equality - LINQ: A Step Ahead Series

Introduction:

LINQ - Language Integreted Query is repeadily used in these days. The presented article is elaborate the idea "How to describe a LINQ Query".

Simply, a query is an expression that retrieves data from a data source.

Scope:
The scope of the presented article is upto its title and projected scenarios.
  • Basics

  • LINQ Actions

  • Some basic example

  • Creating a LINQ project using Visual Studio



Description:

Now lets elaborate the topic in following points:

1. Operation of LINQ Query:

LINQ query consists three distinct actions as defined bellow:

(a) In this step LINQ gather the DataSource it may be any source of data.
(b) In next step have to create the Query
(c) Finally, execute the Query.

Lest, go through the following code-lines and try to understand the above operations:


class LINQQuery
{
static void Main()
{

// This is the Data source - Operation - I
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// Query Creation - Operation - II
var numQuery =
from num in numbers
where (num % 2) == 0
select num;

// Query Execution - Operation - III
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}


Three actions of LINQ Query [adapted from MSDN - bb397906]
LINQ Query Actions

2. Skip and Take:

Skip, SkipWhile, Take, and TakeWhile are used to partition collectionsinto two parts and then return one of the parts. These partition features are only implemented as extension methods.

skip jumps to the indicated argument position in the sequence and returns everything after that.

SkipWhile accepts a predicate and instead of using a position, it skips until the predicate evaluates to false.

Take grabs all of the elements up to the specified position in the index.

TakeWhile grabs all of the items in a sequence as long as the predicate evaluates to true.

3. Create a LINQ Project:

As per MSDN :

To use LINQ to XML or LINQ to DataSet in either C# or VB.Net language, you must manually add namespaces and references as described in the following :

If you are upgrading a project that you created by using an earlier version of Visual Studio, you may have to supply these or other LINQ -related references manually and also manually set the project to target .NET Framework version 3.5.

To target the .NET Framework version 3.5


  1. In Visual Studio, open a Visual Basic or C# project that was created in Visual Studio 2005 and follow the prompts to

    convert it to a Visual Studio 2008 project.

  2. For a C# project, click the Project menu, and then click Properties.

  3. In the Application property page, select .NET Framework 3.5 in the Target Framework drop-down list.

  4. For a Visual Basic project, click the Project menu, and then click Properties.

  5. In the Compile property page, click Advanced Compile Options and then select .NET Framework 3.5 in the Target Framework

    (all configurations) drop-down list.



Important Points:

  1. LINQ queries start with the keyword from.

  2. In a LINQ query, you are always working with objects.

  3. You an apply the basic operations to LINQ Query as follow:



    • Filtering is the common operation tyhrough which you can filter the data, consider following code:


      //filter all employees on last name as 'Arora'
      var lnqueryNames = from empname in employee
      where empname.lastname == "Arora"
      select empname;



    • Ordering sets the ordering for the output, lets take a loon in the following:


      //display all Arora in ascending order with departments
      var lnqueryNames = from empname in employee
      where empname.lastname == "Arora"
      orderby empname.dept ascending
      select empname;



    • Ordering give the output in a group, consider following example:



      var lnqueryNames = from empname in employee
      group empname by empname.department;

      foreach (var empbydept in lnqueryNames)
      {
      Console.WriteLine(empbydept.Key);
      foreach (Employee emp in empbydept)
      {
      Console.WriteLine(" {0}", emp.lastName);
      }
      }

Monday, February 9, 2009

How to Test Anonymous Type Equality - LINQ: A Step Ahead Series

How to Test Anonymous Type Equality - LINQ: A Step Ahead Series

First of all Anonymous Type Equality : If two or more anonymous types have same order, number and member declaratory type amd name then the same anonymous type is defined. So, its permissible to use the referencial equality operator on these types.

Now lets see the other face of the coin means of any of order, number and member declarator type and name is different then different anonymous type is defined for each. Then it throw compiler error while testing referential integrity.

Note:

  • Here you can use reflection to get the type information of anonymous types.

  • Use the Equals method (defined by all objects) to test equality of members.



Lets go through following lines :

var paternalMember = new {Father = "R k Arora", City = "Nangal Dam"};
var maternalMember = new {Mother = "Santosh Arora", City = "New Delhi"};

var fatherHome = new {Father = "R k Arora", City = "Nangal Dam"};
var motherHome = new {City = "New Delhi", Mother = "Santosh Arora"};

//Compare member equality:
paternalMember.Equals(fatherHome); //returns true
paternalMember.Equals(fatherHome); //error


If you want to know more about Anonymous Type-LINQ please refer to Anonymous Types in LINQ : A Step Ahead Series

Friday, February 6, 2009

Anonymous Types in LINQ : A Step Ahead Series

Introduction:

Programers of Visual Basic the keyword 'var' is confusing here as the type variants was used in Visual Basic.

Here, the keyword var tells to compiler emit a strong type based on t5e value of the operation on the right side.

Important:
Anonymous types can be used to initialize simple types like integers and strings.

Rules : Following are the some basic rules to use LINQ Anonymous Types.


  • Anonymous types can't be null.

  • Must always have an initial assignment.

  • Can be used with Simple or complex types, but composite anonymous types require member declaration

    example:
    var mylist = new {Topic="Anonymous-Types" [, declaratory = value, ...]}.

    in above Topic is the member declaratory.

  • Supports intelliSense.

  • Cannot be used for class field.

  • Can be used with arrays.

  • Anonymous types are all derived from the Object type.



Now, lets explore some category or types of anonymous types:

Simple Anonymous Type

With the keyword var and giving the value of the variable in the right side of the assignment operator (=), anyone can declare the Simple anonymous type.

var list = "Anonymous Types in LINQ : A Step Ahead Series";


The anonymous type is assigned to the name on the left side of the assignment operator, and the type emitted by the compiler to Microsoft Intermediate Language (MSIL) is determined by the right side of the operator.

The above line is identical in the MSIL if defined as following:

var list = "Anonymous Types in LINQ : A Step Ahead Series";


Array Initializer Syntax

Anyone can use the Anonymous Type to initialize the array too but with a rigid rule that is : new keyword must have to use.

example:

var myArrayWithAntype = new int[]{ 1, 2, 12, 53, 58, 8, 2113, 2221 };


In above the array is Anonymous as it is defined with Annonymous Type initialize rule.

Composite Anonymous Types : Lets define

Now, lets take a look how to define Composite Anonymous Type. Its called just as class without the "typed" class definition.

var fullname = new {FirstName=”Gaurav”, LastName=”Arora”};


in above 'fullname' contains both first and last name. Go through following:


//throws an error
Console.WriteLine(fullname.FirstName);

//Displays fullname
Console.WriteLine(fullname);


Note :
1. Anonymous types are immutable.
2. Within the scope of article we have supplied a little tricks, there can be generic anonymous methods, you can apply methods, can return anonymous values etc.