Tuesday, August 16, 2011

LINQ: OfType Query Operator?


LINQ comes with the OfType<T> query operator, through which we can filter the required object type from a heterogeneous array.

Suppose below is the scenario where we have array with various types but will only retrieve the string type. Here we go with ease of life,


using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Xml.XLinq;
using System.Data.DLinq;

namespace LINQConsoleApplication1_Oct11
{
    class Program
    {
        static void Main(string[] args)
        {
            object[] numbers = {"Wriju", 28, 12/12/2006, 3.3f, 1, "Tupur", 8.0};
            var strs = numbers.OfType<string>();

            Console.WriteLine("The list of friends..");
            Console.WriteLine("==========================");

            foreach(var s in strs)
            {
                Console.WriteLine(s);
            }
            Console.ReadKey();
        }
    }
}

Output will look like

The list of friends..
==========================
Wriju
Tupur

What are Expression Trees?

Expression tree is the construct that has been developed for remote LINQ model. In a nutshell expression trees provide a separation layer between data source and run time. With the help of avisitor pattern expression tree is interpreted in run time and query object is translated into the presentation that is understandable to the data source. In case of LINQ-to-SQL, expression trees are translated into SQL with column names mapped from XML configuration. The SQL query is sent to the database and the result undergoes similar translation procedure but in the opposite direction.

Use of let and into keyword, and how they help in making Progressive queries but still keep Defered execution.


into and let create temporary reference to store the result of a subquery/subexpression that can be later queried itself. These operators keep deferred execution and allow creation of sub routines that can be used incrementally or progressively. Personally, I would rather try simplifying the query, so I will not use either of these keywords. A few separate queries are much debugger [developer] friendly and less bug prone.
As a sample, let can be used to store the count of elements in a group
var categories = from p in products
	group p by p.Category into g
	let elCount = g.Count()
	select new 
	{ 	Category = g.Key, 
		ElementCount = elCount 
	};

Use of IQueryable and IEnumerable interfaces

IEnumerable<T> is applicable for in-memory data querying, in contrast IQueryable<T> allows remote execution, like web service or database querying. 



First of all, IQueryable<T> extends the IEnumerable<T> interface, so anything you can do with a "plain" IEnumerable<T>, you can also do with an IQueryable<T>.
Misuse of the interface can result in performance and memory problems, e.g. if IEnumerable<T> is used instead of IQueryable<T> to perform paging all the rows from data source will be loaded, instead of only those rows from the current page
IEnumerable<T> just has a GetEnumerator() method that returns an Enumerator<T> for which you can call its MoveNext() method to iterate through a sequence of T.
What IQueryable<T> has that IEnumerable<T> doesn't are two properties in particular—one that points to a query provider (e.g., a LINQ to SQL provider) and another one pointing to a query expressionrepresenting the IQueryable<T> object as a runtime-traversable expression that can be understood by the given query provider (for the most part, you can't give a LINQ to SQL expression to a LINQ to Entities provider without an exception being thrown).
The expression can simply be a constant expression of the object itself or a more complex tree of a composed set of query operators and operands. The query provider's IQueryProvider.Execute() orIQueryProvider.CreateQuery() methods are called with an Expression passed to it, and then either a query result or another IQueryable is returned, respectively.

What are Interpreted Queries?


LINQ combines two architectural models: in-memory local and remote.
The first one is basically LINQ-to-Objects and LINQ-to-XML. Local model closely work withIEnumerable<T> and decorator sequences of C# methods, lambdas and delegates. The query is compiled into standard imperative IL code.
The second one is LINQ-to-SQL and LINQ-to-Entities. Remote model in contrast is rather declarative to the runtime. Sequences in query implement the IQueryable<T> (which in turn derives fromIEnumerable<T>) and after the compilation resolve into query operators from Queryable class – expression trees. Depending on the query provider, expression trees will be later interpreted by the runtime and are “friendly” to the remote data source.



So far, we’ve examined the architecture of local queries,which operate over collections implementing IEnumerable<>. Local queries resolve to query operators in the Enumerable class, which in turn resolve to chains of deco-rator sequences. The delegates that they accept—whether expressed in comprehension syntax, lambdasyntax, or tradi-tional delegates—are fully local to Intermediate Language(IL) code just as any other C# method.
Bycontrast, interpreted queries are descriptive. They operate over sequences that implement IQueryable<>, and they resolve to the query operators in the Queryable class, which emit expression trees that are interpreted at runtime.



There are two IQueryable implementations in the .NET Framework:
•LINQ to SQL
•LINQ to Entities
In addition, the AsQueryable extension method generates an IQueryable wrapper around an ordinary enumerable collection.



What are Interpreted Queries?


LINQ combines two architectural models: in-memory local and remote.
The first one is basically LINQ-to-Objects and LINQ-to-XML. Local model closely work withIEnumerable<T> and decorator sequences of C# methods, lambdas and delegates. The query is compiled into standard imperative IL code.
The second one is LINQ-to-SQL and LINQ-to-Entities. Remote model in contrast is rather declarative to the runtime. Sequences in query implement the IQueryable<T> (which in turn derives fromIEnumerable<T>) and after the compilation resolve into query operators from Queryable class – expression trees. Depending on the query provider, expression trees will be later interpreted by the runtime and are “friendly” to the remote data source

Explain Query Expression syntax, Fluent syntax, Mixed Queries.


Query expression syntax is based on the new keywords such as from, select, join, group by, order byetc.
string[] words = { "roll", "removal", "fuse", "accusation", 
                             "capture", "poisoning", "accusation" };

var query = from w in words
            where w.Length > 4
            orderby w ascending
            select w;
This query selects words with more than 4 letters and presents result in the ascending order. Fluent syntax is based on the regular C# methods that are linked in a chain, like this sample from msdn.
List<Customer> customers = GetCustomerList();
 
var customerOrders = customers
	.SelectMany(
		(cust, custIndex) => cust
			.Orders
			.Select(o => 
				"Customer #" + (custIndex + 1) +
				" has an order with OrderID " + o.OrderID));
Mixed syntax means query expression syntax is mixed with fluent method calls, for example it can be used to get the distinct values, first result or to get items as array (which by the way will trigger immediate query execution)

What is Deffered Execution?

Deferred execution means that the actual work will not be performed immediately, but rather when the result is requested at a latter stage. This is implemented via proxy pattern and perhaps yield return. The benefits of deferred executions are that potential heavy load on CPU, memory or database is delayed to the moment it is absolutely required, therefore saving time say while initialisation.

Why var keyword is used and when it is the only way to get query result?


var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a generalised keyword. The compiler infers the actual type from the static type of the expression used to initialise the variable. One must use var with the query that returns anonymous type. E.g. 
// anonymous type returned
var query = from w in words
            select new
                {
                    LetterCount = w.Length,
                    UpperString = w.ToUpper()
                };

foreach (var item in query)
{
    Console.WriteLine(item.LetterCount + " " + item.UpperString);
}

Monday, August 15, 2011

What are the four LINQ Providers that .NET Framework ships?

1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.

What is the purpose of LINQ Providers in LINQ?

LINQ Providers are a set of classes that takes a LINQ query and dynamically generates a method that executes an equivalent query against a specific data source.

List the important language extensions made in C# to make LINQ a reality?

1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions

How are Standard Query Operators useful in LINQ?


Standard Query Operators in LINQ can be used for working with collections for any of the following and more.
1. Get total count of elements in a collection.
2. Order the results of a collection.
3. Grouping.
4. Computing average.
5. Joining two collections based on matching keys.
6. Filter the results

How are Standard Query Operators implemented in LINQ?

Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collection classes implement IEnumerable interface.

What are the three main components of LINQ or Language INtegrated Query?


1. Standard Query Operators
2. Language Extensions
3. LINQ Providers

What is Quantifiers in reference linq to Dataset?

Quantifier Operators return the Boolean value (either True or false) if some or all the elements in a sequence satisfy a condition,

Mainly two Quantifiers in linq –

Any-
All

Examples (vb)

“Any” to determine if any of the words in the array contain the substring

Public Sub ExampleAny()

Dim words() = {"believe", "relief", "receipt", "field"}

Dim iAfterE = words.Any(Function(w) w.Contains("ei"))

Console.WriteLine("There is a word that contains in the list that contains 'ei': {0}", iAfterE)
End Sub

Result:

There is a word that contains in the list that contains 'ei': True

“All “to return a grouped a list of products only for categories that have all of their products in stock

Public Sub Quantifier_All_Exam()

Dim products = GetProductList()

Dim productGroups = From p In products _
Group p By p.Category Into Group _
Where (Group.All(Function(p) p.UnitsInStock > 0)) _
Select Category, ProductGroup = Group

ObjectDumper.Write(productGroups, 1)
End Sub

Write small Program to generate Xml Document from table like (StudentRecord Table) using linq query


Public void CreateXmlDocFromArray()

{

// Now enumerate over the array to build an XElement.
XElement StudentRecords =
new XElement("StudentInfo",
from c in Student
select new XElement("Student",
new XAttribute("Name", c.Name),
new XElement("RollNo", c.RollNo)
)
);
Console.WriteLine(StudentRecords);
}

List out the Data Context Functions. Where do we use “SubmitChanges()”?

Create Database ()/Delete database ()

Database Exist ( )

Submit Changes ()

Create Query()

Log

SubmitChanges()- SunbmitChanges Data Context Fuction Used to submit any update to the actual database.

Differentiate between Conversion Operator “IEnumerable” and “ToDictionary” of linq.

IEnumerable and To Dictionary both are Conversion Operator which are used to solved to conversion type Problems.

“AsEnumerable ” operator simply returns the source sequence as an object of type IEnumerable<T>. This kind of “conversion on the fly” makes it possible to call the general-purpose extension methods over source, even if its type has specific implementations of them

Signature-

public static IEnumerable<T> AsEnumerable<T>
(
this IEnumerable<T> source
);

“ToDictionary ” Conversion Operator is the instance of Dictionary (k,T) . The “keySelector ”predicate identifies the key of each item while “elementSelector ”, if provided, is used to extract each single item.

Key and elementSelector Predicate can be Used in following ways-

Example-

Public void ToDictionatyExample()
{
Var scoreRecords=
{
new {Name = "Alice",Score = 50 },
new {Name = "Bob",Score = 40 },
new {Name = "Cathy", Score = 45} };
Var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
Console.WriteLine("Bob's score: {0}", scoreRecordsDict("Bob"));
}

Result: Bob's score: { Name = Bob, Score = 40 }

How can we find Sequence of Items in two different array (same Type) in the same order using linq query?

Public void MatchSequenceLinq()
{
var wordsA = {"Rahul","ashok","sweta"};
var wordsB = {"rahul","ashok","sweta"};
var match = wordsA.SequenceEqual(wordsB);
Console.WriteLine("The sequences match: {0}", match);
}

Output Result: True

What is Lambda Expressions? How can we optimize our linq code using this Expression?

Lambda expressions can be considered as a functional superset of anonymous
methods, providing the following additional functionality:

Lambda expressions can infer parameter types, allowing you to omit them.

Lambda expressions can use both statement blocks and expressions as bodies,
allowing for a terser syntax than anonymous methods, whose bodies can
only be statement blocks.

Lambda expressions can participate in type argument inference and
method overload resolution when passed in as arguments. Note: anonymous
methods can also participate in type argument inference (inferred return types).


In C#, a lambda expression is written as a parameter list, followed by the => token,followed by an expression or a statement block

How can you find average of student marks from student tables (Columns are StudentID, Marks)?

Public void LinqToSqlAverage()
{
var query = (from p in db. student. Marks).Average();

Console.WriteLine(q);
}

Write a Program using Skip and Take operators. How can it beneficial for bulky data accessing on page?

“skip” and “take” Operator used for Paging. Suppose we have Customer table of 100 records. To find 10 records by skipping the first 50 records from customer table-

Public void Pagingdatasource ()
{
Var Query =from CusDetails in db.customer skip (50) Take (10)
ObjectDumper.Write(q)
}

Hence The LinQ “ SKIP” operator lets you skip the results you want, and “Take” Operator enables you yo select the rest of result . So By Using Skip and Take Operator, You can create paging of Specific sequence.

What is Linq to SQL Deferred Loading?

Example – Let’s have two tables -

Blogs Table (BlogID ,Blog Name,owner) and Post table ( PostID, BlogID, Title, Body)

To find Name and No’s of posts in each blog-
BlogDataContext ctx = new BlogDataContext( );
var query = from b in ctx.Blogs select b;
foreach (Blog b in query)
{
Console.WriteLine("{0} has {1} posts", b.BlogName, b.Posts.Count);
}


Output of queries Produce Blog name with no’s of post, But For each Blog
Looping will be occurs (in case long list of blogs) that’s reduces Overall Performance that’s called the Deferred loading. 

Can I use LINQ with databases other than SQL Server? Explain how

LINQ supports Objects, XML, SQL, Datasets and entities. One can use LINQ with other databases through LINQ to Objects or LINQ to Datasets, where the objects and datasets then take care of database specific operations and LINQ only needs to deal with those objects, not the database operations directly.

Disadvantages of LINQ over Stored Procedures


  • LINQ needs to process the complete query, which might have a performance impact in case of complex queries against stored procedures which only need serialize sproc-name and argument data over the network.
  • LINQ is generic, whereas stored procedures etc can take full advantage of the complete database features.
  • If there has been a change, the assembly needs to be recompiled and redeployed whereas stored procedures are much simpler to update.
  • It’s much easier to restrict access to tables in database using stored procedures and ACL’s than through LINQ. 

Pros and cons of LINQ (Language-Integrated Query)


Pros of LINQ:
  • Supports type safety
  • Supports abstraction and hence allows developers to extend features such as multi threading.
  • Easier to deploy
  • Simpler and easier to learn
  • Allows for debugging through .NET debugger.
  • Support for multiple databases
Cons of LINQ:
  • LINQ needs to process the complete query, which might have a performance impact in case of complex queries
  • LINQ is generic, whereas stored procedures etc can take full advantage of database features.
  • If there has been a change, the assembly needs to be recompiled and redeployed. 

LINQ - Difference between LINQ and Stored Procedures.


Difference between LINQ and Stored Procedures:
  • Stored procedures normally are faster as they have a predictable execution plan. Therefore, if a stored procedure is being executed for the second time, the database gets the cached execution plan to execute the stored procedure.
  • LINQ supports type safety against stored procedures.
  • LINQ supports abstraction which allows framework to add additional improvements like multi threading. It’s much simpler and easier to add this support through LINQ instead of stored procedures.
  • LINQ allows for debugging using .NET debugger, which is not possible in case of stored procedures.
  • LINQ supports multiple databases against stored procedures which need to be re-written for different databases.
  • Deploying LINQ based solution is much simpler than a set of stored procedures 

LINQ - What is Language Integrated Query (LINQ)?

LINQ is a set of extensions to .NET Framework that encapsulate language integrated query, set and other transformation operations. It extends VB, C# with their language syntax for queries. It also provides class libraries which allow a developer to take advantages of these features.