LINQ in C# - Part 1

Introduction

  • Different languages have been developed over time for the various types of data sources, for example SQL for relational databases and XQuery for XML. 
  • Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. 
  • LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats.
  • Language-Integrated Query (LINQ) is the name for a set of technologies(Lambda Expressions, Expression Trees, Extension methods, Partial methods, Query Expression) based on the integration of query capabilities directly into the C# language. 
  • LINQ family of technologies provides a consistent query experience for objects (LINQ to Objects), relational databases (LINQ to SQL), and XML (LINQ to XML). 
  • A query is an expression that retrieves data from a data source.

Three Parts of a Query Operation

All LINQ query operations consist of three distinct actions:
  • Obtain the data source.
  • Create the query.
  • Execute the query. 
class IntroToLINQ
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2)
== 0
select num;

// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}

The Data Source

  • The data source of LINQ must be of Queryable Types
  • Types that supports IEnumerable / IEnumerable<T> or Types that are derived from IEnumerable such as the generic IQueryable<T> are called Queryable Types

The Query

  • The query specifies what information to retrieve from the data source or sources. Optionally, a query also specifies how that information should be sorted, grouped, and shaped before it is returned. A query is stored in a query variable and initialized with a query expression. 
  • In the above example numQuery is a Query variable, expression after the equal to = operator is called Query expression.

Query Execution

  • Query execution can be of two types
    • Deferred Execution
    • Immediate Execution
  •  Deferred Execution
    • When we assign a Query Expression to a Query Variable, actually the query results are not stored in the Query Variable while the time of assigning.
    • The results are only available at the time of Iterating over the Query Variable
    •  So if there is a change in the Data source after the Query Variable assignment
    •  It will be reflected in the results 
    • Example
class Program
    {
        static void Main(string[] args)
        {
            List<string> greetings = new List<string> { "hello world", "hello LINQ", "hello Apress" };

            Console.WriteLine("Original Source");
            Console.WriteLine("-----------");
            IEnumerable<string> results = greetings.Select(x => x.Split(' ').Last());          
            foreach (var item in results)
                Console.WriteLine(item);

            greetings.Add("hello C#");
         

            Console.WriteLine("After Source Modified");
            Console.WriteLine("-----------");
            foreach (var item in results)
                Console.WriteLine(item);

            Console.ReadLine();
        }
    }
// Output
Original Source
-----------
world
LINQ
Apress
After Source Modified
-----------
world
LINQ
Apress
C#
  •  Immediate Execution
  • Queries that perform aggregation functions over a range of source elements must first iterate over those elements. 
  • Examples of such queries are Count, Max, Average, and First
  • These execute without an explicit foreach statement because the query itself must use foreach in order to return a result. Note also that these types of queries return a single value 
  • To force immediate execution of any query and cache its results, you can call the ToList() or ToArray() methods.
  • Examples
var evenNumQuery = 
from num in numbers
where (num % 2)
== 0
select num;

int evenNumCount = evenNumQuery.Count();
 
List<int> numQuery2 =
(from num in numbers
where (num % 2)
== 0
select num).ToList();

// or like this:
// numQuery3 is still an int[]

var numQuery3 =
(from num in numbers
where (num % 2)
== 0
select num).ToArray();

No comments:

Post a Comment

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...