LINQ interview question and answers
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;
}
No te:
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.
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
Why can't
datareader by returned from a Web Service's Method
Cos, it's not serializable
What is the use of
System.XML.XLinq.dll?
System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML.
What is the use of
System.Data.DLinq.dll?
System.Data.DLinq.dll provides functionality to work with LINQ to SQL.
Which assembly represents
the core LINQ API?
System.Query.dll assembly represents the core LINQ API.
Which class's
extension methods are used in LINQ to SQL?
NOTE: This is objective
type question, Please click question title for correct answer.
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"),
)
);
When
generating database mappings using LINQ to SQL, which tool allows you to create
entity classes using a convenient graphical interface?
NOTE: This is objective type question, Please click question title for correct answer.
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 LINQ?
NOTE: This is objective type question, Please click question title for correct answer.
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
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"), ) ); |
When
generating database mappings using LINQ to SQL, which tool allows you to
create entity classes using a convenient graphical interface?
NOTE: This is objective type question, Please click question title for correct answer. |
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) Thanks and Regards Akiii |
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 LINQ?
NOTE: This is objective type question, Please click question title for correct answer. |
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. Thanks and Regards Akiii |
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. Thanks and Regards Akiii |
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?
Posted by: Niladri.Biswas
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(); |
0 comments:
Post a Comment