Read without ads and support Scribd by becoming a Scribd Premium Reader.
 
Articles of Technology Digestified
LINQ Interview Questions
2011-10-22 00:10:11 Jinal Desai
What is LINQ?
LINQ, or Language INtegrated Query, is a set of classes added to the .NET Framework 3.5. LINQ adds arich, standardized query syntax to .NET programming languages that allows developers to interact withany type of data.
What are the advantages of using LINQ or Language INtegrated Query?
In any data driven application, you get data either from a Database, or an XML file or from collectionclasses. Prior to LINQ, working with each data source requires writing a different style of code. Moreover,working with external resources like data bases, XML files involves communicating with that externalresource in some syntax specific to that resource. To retrieve data from a database you need to send it astring that contains the SQL query to execute, similarly, to work with an XML document involves specifyingan XPath expression in the form of a string. The idea is that using LINQ you can work with disparate datasources using a similar style without having to know a separate syntax for communicating with the datasource (e.g., SQL or XPath) and without having to resort to passing opaque strings to external resources.In any data driven web application or windows application, we use database as a datasource for theapplication. In order to get data from the database and display it in a web or windows application, wetypically do the following.1. Prepare your SQL Statements.2. Execute SQL Statements against the database.3. Retrieve the results.4. Populate the Business Objects.5. Display the Data in the Web Form or Windows From.
public List<Customer> GetCustomerByCity(int CityId){//Connection String = "";string connStr = "";//Prepare the connection object and connect to the databaseSqlConnection conn = new SqlConnection(connStr);//Open Connectionconn.Oepn();//Prepare Querystring query = "SELECT * FROM Customers WHERE CityId = @CityId";//Define command object with parametersSqlCommandcomd = new SqlCommand(query,conn);comd.Parameters.AddWithValue("@CityId", CityId);//Get the DataReaderSqlDataReader reader = comd.ExecuteReader();//Populate list of customersList<Cuustomer> customersList = new List<Customer>();While(reader.Read()){Customer cust = new Customer();cust.Id = reader["Id"].ToString();cust.Name = reader["Name"].ToString();customersList.Add(cust);}//Close Everythingreader.Close();conn.Close();//Return customer listreturn customersList;}
In order to send a query to the database we must first establish a connection to the database. We thenmust encode the logic – the SQL query, its parameters, and the parameters’ values – into strings that aresupplied to the SqlCommand object. And because these inputs are encoded into opaque strings, there isno compile-time error checking and very limited debugging support. For example, if there is a spellingmistake in the SELECT query causing the Customets table name to be misspelled, this typographicalerror won’t show up until runtime when this page is viewed in a web browser. These typographical errors
 
are easy to make as there is no IntelliSense support. When we use LINQ, Visual Studio would display anerror message alerting us about the incorrect table name. Another mismatch between the programming language and the database is that the data returned by thedatabase is transformed for us into objects accessible through the SqlDataReader, but these objects arenot strongly-typed objects like we’d like. To get this data into strongly-typed objects we must write codeourselves that enumerates the database results and populates each record into a corresponding object.LINQ was designed to address all these issues. LINQ also offers a unified syntax for working with data, beit data from a database, an XML file, or a collection of objects. With LINQ you don’t need to know theintricacies of SQL, the ins and outs of XPath, or various ways to work with a collection of objects. All youneed be familiar with is LINQ’s classes and the associated language enhancements centered aroundLINQ.In other words, LINQ provides type safety, IntelliSense support, compile-time error checking, andenhanced debugging scenarios when working with different datasources.
What are the three main components of LINQ or Language INtegrated Query?
1. Standard Query Operators2. Language Extensions3. LINQ Providers
How are Standard Query Operators implemented in LINQ?
Standard Query Operators are implemented as extension methods in .NET Framework. These StandardQuery Operators can be used to work with any collection of objects that implements the IEnumerableinterface. A class that inherits from the IEnumerable interface must provide an enumerator for iteratingover a collection of a specific type. All arrays implement IEnumerable. Also, most of the generic collectionclasses implement IEnumerable interface.
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 andmore.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
List the important language extensions made in C# to make LINQ a reality?
1. Implicitly Typed Variables2. Anonymous Types3. Object Initializers4. Lambda Expressions
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 thatexecutes an equivalent query against a specific data source.
What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects – Executes a LINQ query against a collection of objects2. LINQ to XML – Executes an XPATH query against XML documents3. LINQ to SQL – Executes LINQ queries against Microsoft SQL Server.4. LINQ to DataSets – Executes LINQ queries against ADO.NET DataSets.
Write a program using LINQ to find the sum of first 5 prime numbers?
Class Sample{static void Main(){int[] primeNum = {1, 2, 3, 5, 7};//Use Count() and Sum() Standard Query OperatorsConsole.WriteLine("The Sum of first {0} prime numbers is {1}", primeNum.Count(), primeNum.Sum());}}
What is Lambda Expression?
 A Lambda expression is nothing but an Anonymous Function, can contain expressions and statements.Lambda expressions can be used mostly to create delegates or expression tree types. Lambdaexpression uses lambda operator => and read as ‘goes to’ operator.Left side of this operator specifies the input parameters and contains the expression or statement block at
 
the right side.Example: myExp = myExp/10;Now, let see how we can assign the above to a delegate and create an expression tree:
delegate int myDel(int intMyNum);static void Main(string[] args){//assign lambda expression to a delegate:myDel myDelegate = myExp => myExp / 10;int intRes = myDelegate(110);Console.WriteLine("Output {0}", intRes);Console.ReadLine();//Create an expression tree type//This needs System.Linq.ExpressionsExpression<myDel> myExpDel = myExp => myExp /10;}
Note:
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 methodssuch as Where.
How LINQ is beneficial than Stored Procedure?
There are couple of advantage of LINQ over stored procedures.
1. Debugging
– It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you canuse visual studio’s debugger to debug the queries.
2. Deployment
– With stored procedures, we need to provide an additional script for stored proceduresbut with LINQ everything gets complied into single DLL hence deployment becomes easy.
3. Type Safety
– LINQ is type safe, so queries errors are type checked at compile time. It is really good toencounter an error when compiling rather than runtime exception!
Why Select Clause comes after From Clause in LINQ Query?
The reason is, LINQ is used with C# or other programming languages, which requires all the variables tobe declared first. From clause of LINQ query just defines the range or conditions to select records. Sothat’s why from clause must appear before Select in LINQ.
What is the extension of the file, when LINQ to SQL is used?
The extension of the file is .dbml.
What is the use of System.Data.DLinq.dll?
System.Data.DLinq.dll provides functionality to work with LINQ to SQL.
What is the use of System.XML.XLinq.dll?
System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML.
Which assembly represents the core LINQ API?
System.Query.dll assembly represents the core LINQ API.
What is the benefit of using LINQ on Dataset?
The main aim of using LINQ to Dataset is to run strongly typed queries on Dataset.Suppose we want to combine the results from two Datasets, or we want to take a distinct value from theDataset, then it is advisable to use LINQ.Normally you can use the SQL queries to run on the database to populate the Dataset, but you are notable to use SQL query on a Dataset to retrieve a particular values. To get this you need to use ADO.NETfunctionalities. But, in case of LINQ, it provides more dignified way of querying the Dataset and providessome new features as compared to ADO.NET.
What is the disadvantage of LINQ over stored procedures?
The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures areprecompiled. In case of LINQ the queries need to be compile before the execution. So according to this, Ican say stored procedures are faster in performance as compared to LINQ.
What are Quantifiers?
They are LINQ Extension methods which return a Boolean value1)All
Search History:
Searching...
Result 00 of 00
00 results for result for
  • p.
  • More From This User

    Notes
    Load more