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

Friday, 17 March 2017

Linq interview questions Part-2

1. Ques: What is difference between IEnumerable and IQueryable ?
Answer:
Difference between IEnumerable and IQueryable
IEnumerable
  • IEnumerable exists in System.Collections Namespace.
  • IEnumerable can move forward only over a collection, it can’t move backward and between the items.
  • IEnumerable is best to query data from in-memory collections like List, Array etc.
  • While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.
  • IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
  • IEnumerable supports deferred execution.
  • IEnumerable doesn’t supports custom query.
  • IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
  • Extension methods supports by IEnumerable takes functional objects.
IQueryable
  • IQueryable exists in System.Linq Namespace.
  • IQueryable can move forward only over a collection, it can’t move backward and between the items.
  • IQueryable is best to query data from out-memory (like remote database, service) collections.
  • While query data from database, IQueryable execute select query on server side with all filters.
  • IQueryable is suitable for LINQ to SQL queries.
  • IQueryable supports deferred execution.
  • IQueryable supports custom query using CreateQuery and Execute methods.
  • IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
  • Extension methods supports by IQueryable takes expression objects means expression tree.

2. Ques: What is the difference between Linq to Object and Linq to SQL ?
Answer:
LINQ to Objects queries operate on IEnumerable collections. The query iterates through the collection and executes a sequence of methods (for example, Contains, Where etc) against the items in the collection. 

LINQ to SQL queries operate on IQueryable collections. The query is converted into an expression tree by the compiler and that expression tree is then translated into SQL and passed to the database. 


3. Ques: What is the difference between First() and Single() extension methods in LINQ ?
Answer:
First(): Use Single to retrieve the first (and only) element from a sequence that should contain one element and no more. If the sequence has more than on element your invocation of Single will cause an exception to be thrown since you indicated that there should only be one element.

Single(): Use First to retrieve the first element from a sequence that can contain any number of elements. If the sequence has more than on element your invocation of First will not cause an exception to be thrown since you indicated that you only need the first element in the sequence and do not care if more exist.


4. Ques: What are Quantifiers in Linq ?
Answer:
 Quantifier Operators return the Boolean value (either True or false) if some or all the elements in a sequence satisfy a condition.

1)All
2)Any
3)Contains
4)SequenceEqual

example:
int[] arr={10,20,30};
var b=arr.All(a=>a>20);


5. Ques:  What are the different implementations of LINQ ?
Answer:
Following are the different implementations of LINQ:

LINQ to SQL : This component was introduced in .Net framework version 3.5 that gives a run-time mechanism to manipulate relational data as objects.

LINQ to DataSet : This component facilitates to run simpler and faster query over data which is cached in the DataSet object.

LINQ to XML : Provides an in-memory XML programming interface.

LINQ to Objects : It provides the use of LINQ queries with any IEnumerable or IEnumerable(T)collection directly, without the use of an middle LINQ provider or API, like LINQ to SQL or LINQ to XML.


6. Ques:  What is DataContext class ?
Answer:
The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface.

DataContext class performs the following three tasks:
  • Create connection to database.
  • It submits and retrieves object to database.
  • Converts objects to SQL queries and vice versa.

7. Ques:  What is a LinqDataSource control?
Answer:
The LinqDataSource control enables you to use LINQ. in an ASP.NET Web page by setting the properties in the markup text. You can use the control retrieve or modify data. It is similar to the SqIDataSource andObjectDataSource controls in the sense that it can be used to declaratively bind other ASP.NET controls on a page to a data source. The difference is that instead of binding directly to a database or to a generic class, theLinqDataSource control is designed to bind a LINQ enabled data model.


8. Ques: What is Action in LINQ?
Answer:
Action are generic delegates provided by base class library of .NET. In Action delegate we can only store those methods that have only input parameters and void return types. We can specify upto 16 parameters.
Below is the example of Action delegate:

func f1 = (a, b) => a + b;

Action<int> printAction = (a) => Console.WriteLine(a);
printAction(f1(1, 3));


9. Ques: What is Predicate delegate in LINQ ?
Answer:
Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. Predicate is a delegated provided by base class library of NET.
In Predicate delegate we can only store those method which have one input parameter and a bool return type.
Predicate delegates are mainly used in filtering scenarios in LINQ where we have to filter some list.
It is being used with lambda expression (=>). It takes generic type as an argument.
It allows a predicate function to be defined and passed as a parameter to another function

 Example of Predicate delegate given bellow

Predicate<string> isStringStartWithMChar = (a) => a.StartsWith("m");
Console.WriteLine(isStringStartWithMChar("msmd"));


10. Ques:  What is Func Delegates ?
Answer:
Func delegates are pointers to methods that take one or more parameters and must return a value. There are many overloaded Func delegates. Please see the documentation for a better understanding of those. In this article let's have a general idea of how to use it programmatically.

Usage
  Generelly it's used with anonymous methods.
Example:
Func<int, int, int, long> add = delegate(int a, int b, int c) { return a + b + c; };
 Console.WriteLine(add(2, 3, 4)); 

Thursday, 16 March 2017

Linq interview questions Part-1

1. Ques: What is LINQ ? What are the types of LINQ ?  What are the Advantages and Disadvantages of LINQ ?
Answer:
LINQ stands for Language Integrated Query, is the collection of standard query operators which provides query facilities into.NET framework language like C#, VB.NET.

Types of  LINQ  are 
  • LINQ to Objects
  • LINQ to XML
  • LINQ to Dataset
  • LINQ to SQL
  • LINQ to Entities
Advantages
  • Quick turn around for development
  • Queries can be dynamically
  • Tables are automatically created into class
  • Columns are automatically created into properties
  • Relationship are automatically appeaded to classes
  • Lambda expressions are awesome
  • Data is easy to setup and use
Disadvantages
  • No clear outline for Tiers
  • No good way of view permissions
  • Small data sets will take longer to build the query than execute
  • There is an overhead for creating queries
  • When queries are moved from sql to application side, joins are very slow
  • DBML concurrency issues

2. Ques: What are Lambda expressions ? 
Answer:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. 
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. 

The => operator has the same precedence as assignment (=) and is right-associative. 

Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where and Where(IQueryable, String, array[]).

Ex:
class Program
  {
     delegate int del(int i);
     static void Main(string[] args)
     {
        del myDelegate = y => y * y;
        int j = myDelegate(5);
        Console.WriteLine(j);
        Console.ReadLine();
     }
  }


3. Ques:  What is PLINQ?
Answer:
PLINQ stands for Parallel Language Integrated Query. It is the parallel implementation of LINQ, in which a query can be executed by using multiple processors. PLINQ ensures the scalability of software on parallel processors in the execution environment. It is used where data grows rapidly, such as in telecom industry or where data is heterogeneous.

PLINQ also supports all the operators of LINQ. In addition, you can query 'collections by using PLINQ. It can also run several LINQ queries simultaneously and makes use of the processors on the system. Apart from this, PLINQ uses parallel execution, which helps in running the queries quickly. Parallel execution provides a major performance improvement to PLINQ over certain types of legacy code, which takes too much time to execute.


4. Ques:  What is the difference between the Take and Skip clauses?
Answer:
Take clauses
The Take clause will give you a predefined number of elements.
if you want to return two elements from an array then you can use Take clause.

Skip clauses
The Skip clause will skip the predefined number of elements in the query and returns the remaining elements.
if you want to skip first five strings in an array of strings and want to retrieve the remaining string then you can use Skip clause.


5. Ques:  What is the difference between the Select clause and SelectMany() method in LINQ?
Answer:
Difference between the Select clause and SelectMany clause given as
 Select clause
  • Select operator is used to select value from a collection and 
  • Select operator produce one result value for every source value 
Select Many 
  • SelectMany operator is used to select values from a collection of collection i.e. nested collection.
  • SelectMany produce a single result that contains a concatenated value for every source value.
  • Actually, SelectMany operator flatten IEnumerable<IEnumerable<T>> to IEnumrable<T> i.e. list of list to list.

6. Ques: What are the advantages of LINQ over stored procedure?
Answer:
Advantages of LINQ over stored procedure?

  • Debugging – LINQ supports .Net debugger, so we can easily debug a LINQ query using .NET debugger but it is not supported by SQL stored procedure so it is hard to debug the stored procedure.
  • Deployment – To deploy stored procedure it is necessary to write one more script to run them, while LINQ will complie by a single DLL statement and so the deployment will be simple.
  • Type Safety - As LINQ supports type safety so errors can be type checked in LINQ queries in compile time.It is better to use LINQ as it enable us to identify the errors while compilation rather than runtime execution.

7. Ques: What is the difference between first() and single() extension methods in linq ?
Answer:

First()
It returns First element value from collection of elements or a sequence. It also returns first element of sequence when you specified condition. If result has no element than it will throws InvalidOperationException.

FirstOrDefault( )
FirstOrDefault()  is just like First() except that, if no element match the specified condition than it returns default value of underlying type of generic collection. It does not throw InvalidOperationException if no element found. But collection of element or a sequence is null than it throws an exception.


8. Ques: What is difference between LINQ and Stored Procedures?
Answer:

  • 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