LINQ
LINQ
Language Integrated Query or LINQ is the collection of standard query operators which provides
query facilities into.NET framework language like C#, VB.NET. LINQ is required as it bridges the gap
between the world of data and the world of objects.
LINQ to Objects
LINQ to XML
LINQ to Dataset
LINQ to SQL
LINQ to Entities
Q3: What is LINQ?
LINQ stands for Language INtegrated Query. LINQ allows us to write queries over local collection
objects and remote data sources like SQL, XML documents etc. We can write LINQ query on any
collection class which implements the IEnumerable interface.
Anonymous types are types that are generated by compiler at run time. When we create a anonymous
type we do not specify a name. We just write properties names and their values. Compiler at runtime
create these properties and assign values to them.
Debugging: It is difficult to debug a stored procedure but as LINQ is part of.NET, visual studio
debugger can be used to debug the queries
Deployment: For stored procedure, additional script should be provided but with LINQ
everything gets compiled into single DLL hence deployment becomes easy
Type Safety: LINQ is type safe, so queries errors are type checked at compile time
LINQ providers are set of classes that take an LINQ query which generates method that executes an
equivalent query against a particular data source.
With other programming language and C#, LINQ is used, it requires all the variables to be declared first.
“FROM” clause of LINQ query defines the range or conditions to select records. So, FROM clause must
appear before SELECT in LINQ.
Q9: In LINQ how will you find the index of the element using where() with Lambda Expressions?
In order to find the index of the element use the overloaded version of where() with the lambda
expression:
where(( i, ix ) => i == ix);
Q10: List out the three main components of LINQ?
DataContext class acts as a bridge between SQL Server database and the LINQ to SQL. For accessing
the database and also for changing the data in the database, it contains connections string and the
functions. Essentially a DataContext class performs the following three tasks:
Extension methods are static functions of a static class. These methods can be invoked just like instance
method syntax. These methods are useful when we can not want to modify the class. Consider:
public static class StringMethods
{
public static bool IsStartWithLetterM(this string s)
{
return s.StartsWith("m");
}
}
class Program
{
static void Main(string[] args)
{
string value = "malslfds";
Console.WriteLine(value.IsStartWithLetterM()); //print true;
Console.ReadLine();
}
}
Q13: What is Anonymous function?
An Anonymous function is a special function which does not have any name. We just define their
parameters and define the code into the curly braces.
Consider:
Console.WriteLine(f1(1, 2));
}
Q14: Could you compare Entity Framework vs LINQ to SQL vs ADO.NET with stored
procedures?
Stored procedures:
(++)
Great flexibility
Full control over SQL
The highest performance available
(--)
(++)
Rapid development
Data access code now under source control
You're isolated from changes in DB. If that happens you only need to update your
model/mappings in one place.
(--)
Q15: Could you explian what is the exact deference between deferred execution and Lazy
evaluation in C#?
In practice, they mean essentially the same thing. However, it's preferable to use the term deferred.
Lazy means "don't do the work until you absolutely have to."
Deferred means "don't compute the result until the caller actually uses it."
When the caller decides to use the result of an evaluation (i.e. start iterating through an IEnumerable<T>),
that is precisely the point at which the "work" needs to be done (such as issuing a query to the database).
The term deferred is more specific/descriptive as to what's actually going on. When I say that I am lazy, it
means that I avoid doing unnecessary work; it's ambiguous as to what that really implies. However, when
I say that execution/evaluation is deferred, it essentially means that I am not giving you the real result at
all, but rather a ticket you can use to claim the result. I defer actually going out and getting that result
until you claim it.
In a query expression, it is sometimes useful to store the result of a sub-expression in order to use it in
subsequent clauses. You can do this with the let keyword, which creates a new range variable and
initializes it with the result of the expression you supply.
Consider:
A set of extension methods forming a query pattern is known as LINQ Standard Query Operators. As
building blocks of LINQ query expressions, these operators offer a range of query capabilities like
filtering, sorting, projection, aggregation, etc.
LINQ standard query operators can be categorized into the following ones on the basis of their
functionality.
There may be scenario where we need to execute a particular query many times and repeatedly. LINQ
allows us to make this task very easy by enabling us to create a query and make it compiled always.
Benefits of Compiled Queries:
Query does need to compiled each time so execution of the query is fast.
Query is compiled once and can be used any number of times.
Query does need to be recompiled even if the parameter of the query is being changed.
Consider:
Lambda expression is referred as a unique function use to form delegates or expression tree types, where
right side is the output and left side is the input to the method. For writing LINQ queries particularly,
Lambda expression is used.
Q20: Explain what is the difference between Skip() and SkipWhile() extension method?
Answer
Skip() : It will take an integer argument and from the given IEnumerable it skips the
top n numbers
SkipWhile (): It will continue to skip the elements as far as the input condition is true. It will
return all remaining elements if the condition is false.
Problem
I have a List<bool>. I need to get the indexes of top n items where item value = true.
10011001000
Problem
Given that authorsList is of type List<Author>, how can I delete the Author elements that are
equalling to Bob?
Consider:
Answer
An Expression Tree is a data structure that contains Expressions, which is basically code. So it is a tree
structure that represents a calculation you may make in code. These pieces of code can then be executed
by "running" the expression tree over a set of data.
In LINQ, expression trees are used to represent structured queries that target sources of data that
implement IQueryable<T>. For example, the LINQ provider implements the IQueryable<T> interface for
querying relational data stores. The C# compiler compiles queries that target such data sources into code
that builds an expression tree at runtime. The query provider can then traverse the expression tree data
structure and translate it into a query language appropriate for the data source.
Q24: What is the difference between First() and Take(1)?
Problem
Consider:
Use First() when you know or expect the sequence to have at least one element. In other words, when it
is an exceptional occurrence that the sequence is empty.
Use FirstOrDefault() when you know that you will need to check whether there was an element or
not. In other words, when it is legal for the sequence to be empty. You should not rely on
exception handling for the check. (It is bad practice and might hurt performance).
LINQ to SQL only supports 1 to 1 mapping of database tables, views, sprocs and functions available in
Microsoft SQL Server. It's a great API to use for quick data access construction to relatively well
designed SQL Server databases. LINQ2SQL was first released with C# 3.0 and .Net Framework 3.5.