LINQ Interview Questions and Answers.

What is LINQ?

It stands for Language Integrated Query. LINQ is collection of standard query operators that provides the query facilities into .NET framework language like C# , VB.NET.

How LINQ is beneficial than Stored Procedures?

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 can use visual studio's debugger to debug the queries.

2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but 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 to encounter an error when compiling rather than runtime exception!

Why Select clause comes after from clause in LINQ?

The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that’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 LINQ file extension that interacts with Code Behind's objects.

its .dbml

What is a 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. Lambda expression 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.Expressions

            Expression<myDel> myExpDel = myExp => myExp /10;
 }

Why can't datareader by returned from a Web Service's Method.

Cos, it's not realizable.

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 the Dataset, 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 not able to use SQL query on a Dataset to retrieve a particular values. To get this you need to use ADO.NET functionalities. But, in case of LINQ, it provides more dignified way of querying the Dataset and provides some new features as compared to ADO.NET.

What are the advantages of LINQ over Stored Procedures?

Below is the three advantages of LINQ over stored procedures.
Debugging - As debug point concern, as LINQ is part of .NET, we can use the visual studio's debugger to debug the queries but it is tough to debug the Stored procedure as it will not support the visual studio debugger.

Deployment - In case of deployment, we need to provide an additional script for stored procedures to execute but in case of LINQ, it will complie into single DLL hence deployment becomes easier.

Type Safety - As LINQ is type safe, the queries errors are type checked at compile time. Better suggest to use LINQ because it helps to encounter an error at the compile time rather than at runtime exception.

What is the disadvantage of LINQ over stored procedures?

The disadvantage with LINQ is, it is not a precompiled statement where as stored procedures are precompiled. In case of LINQ the queries need to be compile before the execution. So according to this, I can say stored procedures are faster in performance as compared to LINQ.

What are Quantifiers?

They are LINQ Extension methods which return a Boolean value
1)All
2)Any
3)Contains
4)SequenceEqual

example:
int[] arr={10,20,30};
var b=arr.All(a=>a>20);
-------------------------------------------
Output:
b will return False since all elements are not > 20.

Difference between XElement and XDocument

Both are the classes defined by System.Xml.Linq namespace XElement class
represents an XML fragment
XDocument class represents an entire XML document with all associated meta-data.
example:
XDocument d = new XDocument(
new XComment("hello"),
new XElement("book",
new XElement("bookname", "ASP.NET"),
new XElement("authorname", "techmedia"),
)
);

Briefly can you explain the purpose of LINQ providers ?

They are a set of classes that takes a LINQ query and dynamically generates on the fly query which is executed against a specific data source(sql database, oracle, xml file, array...etc)

What is the difference between N-layer and N-tier architecture?

N-layers of application may reside on the same physical computor(same tier) and the components in each layer communicates with the components of other layer by well defined interfaces.Layered architecture focuses on the grouping of related functionality within an application into distinct layers that are stacked vertically on top of each other.Communication between layers is explicit and loosely coupled.With strict layering, components in one layer can interact only with componentsin the same layer or with components from the layer directly below it.
The main benefits of the layered architectural style are:
Abstraction,Isolation, Manageability, Performance, Reusability, Testability.

N-tiers architectue usually have atleast three separate logical parts,each located on separate physical server.Each tier is responsible with specific functionality.Each tier is completely independent from all other tier, except for those immediately above and below it.Communication between tiers is typically asynchronous in order to support better scalability.

The main benifit of tier achitecture styles are
1.Maintainability. Because each tier is independent of the other tiers, updates or changes can be carried out without affecting the application as a whole.
2.Scalability. Because tiers are based on the deployment of layers, scaling out an application is reasonably straightforward.
3.Flexibility. Because each tier can be managed or scaled independently, flexibility is increased.
4.Availability. Applications can exploit the modular architecture of enabling systems using easily scalable components, which increases availability.

Tell me the exact difference between IQueryable and IEnumerable interface ?

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

What is the difference between Count() and LongCount() extension methods in LINQ ?

public static long display()

        {
            var tempval = (from h in objDB.tbl_mvc_login
            select h).Count ();
            return tempval;
        }
public static long display()

        {
            var tempval = (from h in objDB.tbl_mvc_login
            select h).LongCount ();
            return tempval;
        }
 
Look carefully to the above methods declared. They both does the same thing but LongCount() has a greater range than Count(). According to MSDN, it has the range from
long.MinValue = -9223372036854775808
long.MaxValue =  9223372036854775807 
which is quite big. Its DotNet Framework type is System.Int64. While count() DotNet Framework type is System.Int32 which has a range from
long.MinValue = -2,147,483,648
long.MaxValue =  2,147,483,647 
So, next time if you want to count something which is quite big then use LongCount() extension method otherwise use Count().

Can you explain in brief about Aggregate() extension method in LINQ ?

public static int display()

        {
            int[] numbersArray = { 1, 2, 3, 4, 5 };
                  
            return numbersArray.Aggregate((x1, x2) => x1 * x2);
        }
output : 120 In the above code, "numbersArray" is an integer array. Here, the first one being the first number or the previous result, and the second one is the second or next number to participate the calculation.
The calculation goes like :-

1 * 1 = 1 (stored in x1)

x1 * 2 = 2 (stored in x1)

x1 * 3 = 6 (stored in x1)

x1 * 4 = 24 (stored in x1)

x1 * 5 = 120 (stored and returned back)

What is the difference between FirstOrDefault() and SingleOrDefault() extension method in LINQ ?

FirstOrDefault() = gets the first item that matches a given criteria.
SingleOrDefault() = if you specify this extension method that means you are specifically saying that there can be only one value that matches the criteria. If there are more then 1 value that matches the criteria, throw an exception.

What is the difference between First() and Single() extension methods in LINQ ?

First() - There is at least one result, an exception is thrown if no result is returned.
Single() - There is exactly 1 result, no more, no less, an exception is thrown if no result is returned.

How to get the Value of attribute from XML using XDocument class?

Let us look at the below situation
<?xml version='1.0' encoding='UTF-8'?>

  <Countries>

 <State Name = 'Karnataka'>

  <City Name='Bangalore' />  

                <City Name= 'Guledgudda' />   

                <City Name= 'Hubli' />  

                <City Name= 'Tumkur' />                         

 </State>  

   </Countries>

The challenge is to get the City Names using XDocument class. The below code will help us to do so
string inputXml = @"<?xml version='1.0' encoding='UTF-8'?>

       <Countries>

   <State Name = 'Karnataka'>

    <City Name='Bangalore' />  

                         <City Name= 'Guledgudda' />   

                         <City Name= 'Hubli' />  

                         <City Name= 'Tumkur' />                         

   </State>  

       </Countries>";

XDocument countrySource = XDocument.Parse(inputXml);  

//The query      
countrySource

.Descendants("State")

.SelectMany(i => i.Elements())

.ToList()

.ForEach(i=>Console.WriteLine((string)i.Attribute("Name")));

//Output
Bangalore
Guledgudda
Hubli
Tumkur

Explain with an example how to perform group by in LINQ/LAMBDA?

Consider the below input
var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

The problem is to write a query using LINQ and LAMBDA that will count the nunber of fruits.

Solution
var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };
         
//Using LINQ

(from a in input

 group a by a into g

 select new

 {

   Key = g.Key

   ,Count = g.Count()

 })

 .ToList()

 .ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));

//Using Lambda

 input

 .GroupBy(g => g)

 .Select(i => new { Key = i.Key, Count = i.Count() })

 .ToList()

 .ForEach(i => Console.WriteLine("Number of {0} is {1}", i.Key, i.Count));

Output
Number of Apple is 3

Number of Banana is 1

Number of Mango is 2

Number of Orange is 1

Number of Strawberry is 1

How to assign a computed value to the same array back?

Consider the below input
var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };

The problem is to write a query using LINQ that will count the number of fruits and will assign back the value to the same array i.e. we should not create another array for storing the computed values.

Solution

var input = new string[] { "Apple", "Banana", "Mango", "Apple", "Orange", "Mango", "Strawberry", "Apple" };
      
input = (from a in input

        group a by a into g

        where g.Count() >= 2

        select g.Key + " ( " + g.Count() + " )").ToArray();
Output
Apple ( 3 )
Mango ( 2 )

How will you obtain the length of the longest string in a Data table assuming that every column in of type string using Lambda?

DataTable dt = new DataTable();
var maxLength = dt.AsEnumerable()

                  .SelectMany(r => r.ItemArray.OfType<string>())

                  .Max(i => i.Length);


First cast the Datatable to System.Collections.Generic.IEnumerable<T> object by using the AsEnumerable() extension method,then using the SelectMany extension method
to find out the items in the ItemArray whose type is string and finally figuring out the max length of the records.

How will you obtain the length of the longest string in every column of a Datatable assuming that every column in of type string using Lambda?

DataTable dt = new DataTable();

  var maximumColumnsLengths =

                        Enumerable.Range(0, dt.Columns.Count)

                        .Select(col => dt.AsEnumerable()

                        .Select(row => row[col]).OfType<string>()

                        .Max(val => val.Length)).ToList();
 

Write a code snippet for Left outer join using LINQ?

I failed to answer this question in my interview session. So I searched the answer for the question and found in MSDN. After my understanding I just wrote a simple program to understand the left outer join in LINQ.

namespace LeftOuterJoin

{    namespace LeftOuterJoin

    {
        class Employee
        {
            public string EmpName { get; set; }

            public int EmpAge { get; set; }

            public string EmpDeptID { get; set; }
        }
        class Department
        {
            public string DeptID { get; set; }

            public string DeptName { get; set; }
        }

        class Program

        {
            public static void Main(string[] args)
            {
                Employee objEmp1 = new Employee { EmpName = "Naga", EmpAge = 29, EmpDeptID = "1" };

                Employee objEmp2 = new Employee { EmpName = "Sundar", EmpAge = 30, EmpDeptID = "2" };

                Employee objEmp3 = new Employee { EmpName = "Siva", EmpAge = 28, EmpDeptID = "3" };

                Employee objEmp4 = new Employee { EmpName = "Shankar", EmpAge = 31, EmpDeptID = "4" };

                Department objDept1 = new Department { DeptID = "1", DeptName = "IT" };

                Department objDept2 = new Department { DeptID = "2", DeptName = "Admin" };

                Department objDept3 = new Department { DeptID = "3", DeptName = "Testing" };

                Department objDept4 = new Department { DeptID = "4", DeptName = "HR" };

                Department objDept5 = new Department { DeptID = "5", DeptName = "Sales" };

                //Creating List of Objects

                List<Employee> employees = new List<Employee> { objEmp1, objEmp2, objEmp3, objEmp4 };

                List<Department> depts = new List<Department> { objDept1, objDept2, objDept3, objDept4, objDept5 };

                //Left Side Department Right side Employee

                var DeptEmpCollection = from dept in depts

                                        join emp in employees on dept.DeptID equals emp.EmpDeptID into de

                                        from Employees in de.DefaultIfEmpty()

                                        select new { dept.DeptName, EmployeesName = (Employees == null ? "--No Employee--" : Employees.EmpName) };

                foreach (var EmpDept in DeptEmpCollection)
                {
                    Console.WriteLine("Dept {0}, EmpName {1}", EmpDept.DeptName, EmpDept.EmployeesName);
                }
                Console.Read();
            }
        }
    }
}

Write a query to get the single employee name when there are many employees whose name is "test" in the database ?

var employee = (from h in contextobject.Employee 

                where h.EmployeeName == "test"

                select h).FirstOrDefault<Employee>();

Write a query to get the list of all employees whose name is "test" ?

var employeeList = (from h in context.Employee

                    where h.EmployeeName == "test"
                    select h).ToList<Employee>();

IEnumerable Vrs IQueryable

IEnumerable Vrs IQueryable
In Linq, to query data from database and collections we use IEnumerable and IQueryable. IEnumerable is inherited by IQueryable, so it has all features of it and of its capabilities. Both has their own importance to query data and data manipulation.
IEnumerable :-

1. It exists in System.Collection namespace.
2. It can move forward only over collection.
3. It is best to query data from in-memory collections like Array, List, etc.
4. It is suitable for Linq to Objects and Linq To Xml queries.
5. It doesn't support lazy loading, hence not suitable for paging like scenario.

DataContextClasses db= new DataContextClasses();
IEnumerable<Employee>List =dc.Employees.Where(m=>m.Name.StartsWith("a"));
list=list.Take<Employee>(10);

IQueryable :-
1. It exists in System.Linq namespace.
2. It can move forward only over collection.
3. It is best to query data from out-memory like remote database.
4. It is suitable for Linq to Sql queries.
5. It support lazy loading, hence suitable for paging like scenario.

DataContextClasses db= new DataContextClasses();
IQueryable<Employee>List =dc.Employees.Where(m=>m.Name.StartsWith("a"));
list=list.Take<Employee>(10);

What is different between LINQ and Stored Procedure?

1.We can debug LINQ as it is part of .Net, whereas Stored procedure can’t be.
2. Deployment is easy with LINQ as everything compiled into DLL whereas with Stored procedure script is required for deployment.
3. At compile time we can find error, if any in LINQ but it not possible with Stored procedure.

Disadvantage of LINQ over Stored procedure?

Stored procedure compiles one time and executed every time whereas LINQ compiled everytime , so Stored Procedure is faster as compare to LINQ.

What is var?

Var is used to declare implicitly typed local variable means it tells compiler to figure out the type of the variable at compile time.
Since, 'var' is anonymous type, hence it is used where we don't know the type of output like joining of two tables.
var q = (from e in tblEmployee
join d in tblDepartment
on e.DeptID equals d.DeptID
select new
{
e.EmpID, e.FirstName, d.DeptName
});

What is the purpose of SequenceEqual?

The SequenceEqual operator determines whether all elements in two collections are equal and in the same order.
e.g.

using System;
using System.Linq;

class Program

{
    static void Main()

    {
 string[] array1 = { "dot", "net", "perls" };

 string[] array2 = { "a", "different", "array" };

 string[] array3 = { "dot", "net", "perls" };

 string[] array4 = { "DOT", "NET", "PERLS" };

 bool a = array1.SequenceEqual(array2);
 bool b = array1.SequenceEqual(array3);
 bool c = array1.SequenceEqual(array4, StringComparer.OrdinalIgnoreCase);
 Console.WriteLine(a);
 Console.WriteLine(b);
 Console.WriteLine(c);
    }
}
Output
False
True
True

What is the purpose of ElementAt?

The ElementAt operator retrieves the element at a given index in the collection.
e.g.
string[] names =
                { "Niladri", "Arina", "Bob","Foo", "Bar" };
            Random random = new Random(DateTime.Now.Millisecond);
            string name = names.ElementAt(3);
            Console.WriteLine("The name chosen is '{0}'.", name);         
            /*
             This code produces the following sample output:
             The name chosen at random is 'Foo'.
            */

What is the purpose of SingleOrDefault?

  1. Gets the first item that matches a given criteria.
  2. There can be only one value that matches the criteria. If there are more than 1 value that matches the criteria, throw an exception
  3. None of the above
  4. All of the above

What is the difference between IQueryable and IEnumerable interface?

 IEnumerable<T> is applicable for in-memory data querying, and in contrast IQueryable<T> allows remote execution, like web service or database querying.
  1. IQueryable<T> is applicable for in-memory data querying, and in contrast IEnumerable<T> allows remote execution, like web service or database querying
  2. None of the above

How can we handle concurrency in LINQ?

  1. KeepCurrentValues
  2. OverwriteCurrentValues
  3. KeepChanges
  4. All of the above

What is Language Integrated Query (LINQ)?

  1. LINQ is a programming model
  2. LINQ is hardware
  3. LINQ is a firmware
  4. LINQ is a network protocol.

Write the basic steps to execute a LINQ query.?

  1. Obtain the data source (The data source can be either an SQL database or an XML file)
  2. Create a query
  3. Execute the query
  4. All of the above

 

7 comments:

  1. http://www.indiabix.com/technical/dotnet/
    for interview Ques Ans link.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. http://www.sqlaspnet.com/interview/LINQ/

    ReplyDelete
  5. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net course fees | best dot net training in chennai

    ReplyDelete
  6. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net course fees | best dot net training in chennai

    ReplyDelete

Powered by Blogger.