Tuesday, February 17, 2015

LINQ IQ's


LINQ IQ's
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)

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().


Thanks and Regards
Akiii

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)



Thanks and Regards
Akiii

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?


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>();




Thanks and Regards
Akiii

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>();




Thanks and Regards
Akiii

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 Language Integrated Query (LINQ)?


NOTE: This is objective type question, Please click question title for correct answer.

Write the basic steps to execute a LINQ query


NOTE: This is objective type question, Please click question title for correct answer.

What is the function of the DISTINCT clause in a LINQ query


NOTE: This is objective type question, Please click question title for correct answer

What is Object Relational Designer (0/R Designer)?


NOTE: This is objective type question, Please click question title for correct answer.

On what parameter does the GroupBy clause group the data?


NOTE: This is objective type question, Please click question title for correct answer.

How can you open the O/R Designer?


NOTE: This is objective type question, Please click question title for correct answer.

What are lambda expressions in LINQ?


NOTE: This is objective type question, Please click question title for correct answer.

Name the control that exposes the LINQ features to Web developers through the ASP.NET data-source control architecture


NOTE: This is objective type question, Please click question title for correct answer.








What will be the output of 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();


NOTE: This is objective type question, Please click question title for correct answer.

What is the purpose of SingleOrDefault?


NOTE: This is objective type question, Please click question title for correct answer.

What is the difference between IQueryable and IEnumerable interface?


NOTE: This is objective type question, Please click question title for correct answer.

Difference between XElement and XDocument


NOTE: This is objective type question, Please click question title for correct answer.

How can we handle concurrency in LINQ?


NOTE: This is objective type question, Please click question title for correct answer.

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 output of the following query? SELECT EnrollmentDate, COUNT(*) AS StudentCount FROM Person WHERE EnrollmentDate IS NOT NULL


In the below query, we have a table named Person containing EnrollmentDate and so on. This Enrollment column allows nulls while insertion. We are performing the select command based on EnrollmentDate column which is not null. ie, first it checks only for the rows that contain a value in the Enrollment column, then performs GroupBy.
Then it searches for the rows that contains the same EnrollmentDate, counts the number of rows and displays them in the StudentCount column.

Suppose if we have a table like below:

EnrollmentDate Name
01-01-2013 aaaaaaaa
01-05-2013 bbbbb
01-01-2013 ccccccc
01-01-2013 ddddd

Then the ouput will be
EnrollementDate StudentCount
01-01-2013 3
01-05-2013 1




What is the output of the following qury? SELECT EnrollmentDate, COUNT(*) AS StudentCount FROM Person WHERE EnrollmentDate IS NOT NULL


NOTE: This is objective type question, Please click question title for correct answer.




What is the meaning of the following query? Select EnrollmentDate, Count(*) AS StudentCount From TableName GROUPBY EnrollmentDate


The AS clause holds the column name that you want to give.
Hence in the result, the column name for the count will be StudentCount whereas if you dont specify the AS clause then in the result it shows No column name because this column(Count) doe not exist in your database.




What is the output of the following query? var query = from student in students group student by student.Last[0];


In this students in a table name and student is the alias name given to it.
This query is used for grouping the students based on the first letter of their LastName.

Write a program using Linq to create a sequence that contains common first letter from both Product and Customer names?


var productFirstChar = from P in Products
select P.ProductName[0];

var customerFirstChar = from C in Customers
select C.CompanyName[0];

var commonFirstChar = productFirstChar.Intersect(customerFirstChar );

How can we write the Linq query for selecting a set of first authors in the books containing the word 'our' in the title, using local variables?


IEnumerable<Author> firstAuthors = from b in books
let title = b.Title
let authors = b.Authors
where title.Contains("our")
select authors[0];

foreach (Author author in firstAuthors)
Console.WriteLine("Author - {0}, {1}",
author.LastName, author.FirstName);

Tell us about the 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.

Which are the rules apply to a variable scope in lambda expressions?


1). A variable used in lambda expression won't be garbage-collected until the delegate that references that variable is out of the scope.
2). Variables used in a lambda expression won’t be accessible in the parent method.
3). A lambda expression can’t get a ref or out parameter from an containing method.
4). The return statement used in a lambda expression won’t return for the enclosing method.
5). A lambda expression does not support a goto, break or continue statement who point t outer the body
1. What is Language Integrated Query (LINQ)?
LINQ is a programming model that is the composition of general-purpose standard query operators that allow you to work with data, regardless of the data source in any .NET based programming language. It is the name given to a set of technologies based on the integration of query capabilities into any .NET language.
2. What are LINQ query expressions?
A LINQ query, also known as a query expression, consists of a combination of query clauses that identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It specifies what information should be retrieved from the data source.
3. Write the basic steps to execute a LINQ query.
The following are the three basic steps to execute a LINQ query:
Obtain the data source (The data source can be either an SQL database or an XML file)
Create a query
Execute the query
4. Write the basic syntax of a LINQ query in Visual Basic as well as in C#.
In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with the Select or Group Byclause. In addition, you can use the Where, Order By, and Order By Descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

In C#, the basic syntax of a LINQ query starts with the From clause and ends with the Select or group by clause. In addition, you can use the where, orderby, and Orderby descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.
5. In which statement the LINQ query is executed?
A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement in C#.
6. In LINQ, lambda expressions underlie many of the standard query operators. Is it True or False?
It is true
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.
8. What are the different Visual Basic features that support LINQ?
Visual Basic includes the following features that support LINQ:
Anonymous types - Enables you to create a new type based on a query result.
Implicitly typed variables - Enables the compiler to infer and assign a type when you declare and initialize a variable.
Extension method - Enables you to extend an existing type with your own methods without modifying the type itself.
9. What is the function of the DISTINCT clause in a LINQ query?
The DISTINCT clause returns the result set without the duplicate values.
10. What is the DataContext class and how is it related to LINQ?
After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. 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.
11. What is the difference between the Take and Skip clauses?
The Take clause returns a specified number of elements. For example, you can use the Take clause to return two values from an array of numbers. The Skip clause skips the specified number of elements in the query and returns the rest. For example, you can use the Skip clause to skip the first four strings in an array of strings and return the remaining array of string.
12. What is Object Relational Designer (0/R Designer)?
The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and associations (relationships) that are based on objects in a database.
13. Which interface implements the standard query operators in LINQ?
The standard query operators implement the IEnumerable<T> or the IQueryable<T> interface in C# and theIEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic.
14. What are standard query operators in LINQ?
The standard query operators in LINQ are the extension methods that form the LINQ pattern. These operators form an API that enables querying of any .NET array or collection. It operates on sequences and allows you to perform operations, such as determining if a value exists in the sequence and performing an aggregated function, such as a summation over a sequence.
15. On what parameter does the GroupBy clause group the data?
The GroupBy clause groups the elements that share a common attribute.
16. What is a LinqDataSource control?
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.
17. How can you open the O/R Designer?
You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project.
18. The standard query operators are themselves a set of extension methods that provide the LINQ query functionality for any type that implements the IEnumerable<T> interface in Visual Basic. Is it True or False?
False, as it implements the IEnumerable(T) interface in Visual Basic and the IEnumerable<T> interface is implemented in C#.
19. What are lambda expressions in LINQ?
A lambda expression is a function without a name that calculates and returns a single value. All lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.
20. Before you query a DataSet object by using LINQ to DataSet, you must first populate the dataset How can you do this?
You can load the data into the dataset by using different methods, such as:
Using the DataAdapter class
Using LINQ to SQL
21. What are the different implementations of LINQ?
The different implementations of LINQ are:
LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-time infrastructure to manage relational data as objects.
LINQ to DataSet - Refers to a component that makes it easier and faster to query over data cached in a DataSet object.
LINQ to XML - Provides an in-memory XML programming interface.
LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable(T) collection directly, without the use of an intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML.
22. Which command-line tool generates code and mapping for the LINQ to SQL component of .NET Framework?
The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.
23. Name the control that exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.
The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.
24. What is the difference between the Select clause and SelectMany() method in LINQ?
Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, the SelectMany() method produces a single result that contains a concatenated collection from the query.
25. Which extension method do you need to run a parallel query in PLINQ?
The AsParallel extension method is required to run a parallel query in PLINQ
Question 1: Using LINQ, determine if any word in a list contains the substring “ei”.

    string[] words = { "believe", "relief", "receipt", "field" };
    bool iAfterE = words.Any(w => w.Contains("ei"));
    Console.WriteLine("list has words that contains 'ei': {0}", iAfterE);



Question 2: Using LINQ, return a grouped list of products only for categories that have at least one product that is out of stock.


In this case, we run any over a grouping as shown below:



    List<Product> products = GetProductList();
    var productGroups =
        from p in products
        group p by p.Category into g
        where g.Any(p => p.UnitsInStock == 0)
        select new { Category = g.Key, Products = g };


Question 3: Determine if an array of numbers contains all odds.


int[] numbers = { 1, 11, 3, 19, 41, 65, 19 };
bool onlyOdd = numbers.All(n => n % 2 == 1);
Console.WriteLine("The list contains only odd numbers: {0}", onlyOdd);


Question 4: Using LINQ, return a grouped list of products only for categories that have all of their products in stock.



    List<Product> products = GetProductList();

    var productGroups =
        from p in products
        group p by p.Category into g
        where g.All(p => p.UnitsInStock > 0)
        select new { Category = g.Key, Products = g };
Question 1: How can you sort a result set based on 2 columns?
Assume that you have 2 tables – Product and Category and you want to sort first by category and then by product name.
var sortedProds = _db.Products.Orderby(c => c.Category).ThenBy(n => n.Name)
Question 2: How can you use LINQ to query against a DataTable?
You cannot query against the DataTable's Rows collection, since DataRowCollection doesn't implementIEnumerable<T>. You need to use the AsEnumerable() extension for DataTable. As an example:
var results = from myRow in myDataTable.AsEnumerable()
where myRow.Field<int>("RowNo") == 1
select myRow;

Question 3: LINQ equivalent of foreach for IEnumerable<T>
There is no ForEach extension for IEnumerable; only for List. There is a very good reason for this as explained by Eric Lippert here.
Having said that, there are two ways you can solve this:
Convert the items to list and then do a foreach on it:
items.ToList().ForEach(i => i.DoStuff());
Or, alternatively, you can write an extension method of your own.

public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}

Question 4: When to use .First and when to use .FirstOrDefault with LINQ?
You should use First when you know or expect the sequence to have at least one element. In other words, when it is an exceptional if 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.
Question 5: Write a LINQ expression to concatenate a List<string> in a single string separated by a delimiter.
First of all, it is better to use string.Join to tackle this problem. But for interview purposes, this problem can be approached as follows:
string delimeter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimeter + j));
Question 6: Write a LINQ expression to concatenate a List<MyClass> objects in a single string separated by a delimiter. The class provides a specific property (say Name) that contains the string in question.
items.Select(i => i.Name).Aggregate((i, j) => i + delimeter + j)
LINQ JOIN interview questions
The JOIN clause is one of the most complex and potentially confusing aspects of LINQ. A thorough understanding of the JOIN clause can help you glide easily through the interview process. Most of the interview questions that I see around JOIN using LINQ are both direct (and simple) JOIN queries and in a few cases in-direct applications of the JOIN clause. If the position requires extensive SQL or LINQ expertise, you probably would already be familiar with complex joins.
Well, so what does a JOIN clause do? The join clause is useful for associating elements from different source sequences that have no direct relationship in the object model. The only requirement is that the elements in each source share some value that can be compared for equality. For example, a food distributor might have a list of suppliers of a certain product, and a list of buyers. A join clause can be used, for example, to create a list of the suppliers and buyers of that product who are all in the same specified region. Let’s explore this notion with a few examples.
Question: For all the categories in the database, list the products in those categories. In addition, the output should just include the product and category names.
This is a simple JOIN between the products and the categories.

var innerGroupJoinQuery =
    from category in categories // for all categories
    // join with product table on product category ID
    join prod in products on category.ID equals prod.CategoryID into prodGroup
    // create a new object with just the product and category names
    select new { CategoryName = category.Name, Products = prodGroup };


Note that in this code example, if an element from categories has no matching products, that category will not appear in the results. We will review how to fix that using LEFT OUTER JOIN below.

Question: For all the categories in the database, list the products in those categories. If a category does not have any products, still list the category.
In a left outer join, all the elements in the left source sequence are returned, even if no matching elements are in the right sequence. To perform a left outer join in LINQ, use the DefaultIfEmpty method in combination with a group join to specify a default right-side element to produce if a left-side element has no matches.

var leftOuterJoinQuery =
    from category in categories
    join prod in products on category.ID equals prod.CategoryID into prodGroup
    from item in prodGroup.DefaultIfEmpty(new Product{Name = String.Empty, CategoryID = 0})
        select new { CatName = category.Name, ProdName = item.Name };


Question: Given simple data structures of Person (Name) and Pet (Name, Owner), write a LINQ query that lists all the pets that each person owns.
This is a more complex example involving GROUP JOINS. The group join is useful for producing hierarchical data structures. It pairs each element from the first collection with a set of correlated elements from the second collection. GroupJoin has no direct equivalent in traditional relational database terms. However, this method does implement a superset of inner joins and left outer joins. Both of these operations can be written in terms of a grouped join.
So, our basic data structures can be represented as:

class Person
{
    public string Name { get; set; }
}
   
class Pet
{
    public string Name { get; set; }
    public Person Owner { get; set; }
}

And some sample data might look like this

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
Pet boots = new Pet { Name = "Boots", Owner = terry };
Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte };
Pet daisy = new Pet { Name = "Daisy", Owner = magnus };

List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy };


Now we have two ways to implement the same LINQ query. Using the traditional syntax:

// Create a list where each element is an anonymous type
// that contains the person's first name and a collection of
// pets that are owned by them.
var query = from person in people
            join pet in pets on person equals pet.Owner into gj
            select new { OwnerName = person.Name, Pets = gj };


Using the Lambda syntax:

// Create a list where each element is an anonymous
// type that contains a person's name and
// a collection of names of the pets they own.
var query =
    people.GroupJoin(pets,
           person => person,
           pet => pet.Owner,
           (person, petCollection) =>
               new
               {
                   OwnerName = person.Name,
                   Pets = petCollection.Select(pet => pet.Name)
               });


Now for debugging purposes, we can spew out the info as:

foreach (var v in query)
{
    // Output the owner's name.
    Console.WriteLine("{0}:", v.OwnerName);
    // Output each of the owner's pet's names.
    foreach (Pet pet in v.Pets)
        Console.WriteLine("  {0}", pet.Name);
}


This should produce an output similar to the following.
/*
Hedlund, Magnus:
  Daisy
Adams, Terry:
  Barley
  Boots
Weiss, Charlotte:
  Whiskers
*/
P
Question: Given a list of student grades, skip the top 3 grades and find the remaining.
For this question, we will use the SKIP method. SKIP bypasses a specified number of elements in a sequence and then returns the remaining elements.

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

 IEnumerable<int> lowerGrades =
     grades.OrderByDescending(g => g).Skip(3);
   
 Console.WriteLine("All grades except the top three are:");
 foreach (int grade in lowerGrades)
 {
     Console.WriteLine(grade);
 }

 /*
  This code produces the following output:

  All grades except the top three are:
  82
  70
  59
  56
 */



Question: Find out all students who have a grade value of less than 80.
This question is slightly different from the above in the sense that we do not know how many grades to skip. In this case, we will use the SKIPWHILE method. It bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements.

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };

IEnumerable<int> lowerGrades =
    grades
    .OrderByDescending(grade => grade)
    .SkipWhile(grade => grade >= 80);
   
Console.WriteLine("All grades below 80:");
foreach (int grade in lowerGrades)
{
    Console.WriteLine(grade);
}

/*
 This code produces the following output:

 All grades below 80:
 70
 59
 56
*/



There is another variation of SkipWhile that takes into account the index position of the element in the sequence.It bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. The element's index is used in the logic of the predicate function.
Question: For a given integer sequence, skip elements as long as they are 1000 times more than their position in the sequence.

int[] amounts = { 5000, 2500, 9000, 8000,
                    6500, 4000, 1500, 5500 };
   
IEnumerable<int> query =
    amounts.SkipWhile((amount, index) => amount > index * 1000);
   
foreach (int amount in query)
{
    Console.WriteLine(amount);
}

/*
 This code produces the following output:

 4000
 1500
 5500
*/



SKIP and TAKE functions are exact opposites of each other.
Question: Find the top 3 grades.
To solve this question, we will first sort our sequence in descending order and then take the top 3 elements.

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };
   
IEnumerable<int> topThreeGrades =
    grades.OrderByDescending(grade => grade).Take(3);
   
Console.WriteLine("The top three grades are:");
foreach (int grade in topThreeGrades)
{
    Console.WriteLine(grade);
}
   
/*
 This code produces the following output:

 The top three grades are:
 98
 92
 85
*/



Question: In a given sequence of fruit names, find all the fruits that come before orange.
This question requires us to use the TakeWhile function which returns elements from a sequence as long as a specified condition is true.

string[] fruits = { "apple", "banana", "mango", "orange",
                       "passionfruit", "grape" };
   
 IEnumerable<string> query =
     fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
   
 foreach (string fruit in query)
 {
     Console.WriteLine(fruit);
 }
   
 /*
  This code produces the following output:

  apple
  banana
  mango
 */




Another variation of TakeWhile (similar to SkipWhile) takes into account the position of the element in the sequence. Let’s modify our above question to include this new twist. It returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.

Question: Find all the fruits in a sequence as long as their name length is more than the position they occupy in the sequence.
Given all the questions we have been answering till now, this should be very intuitive to answer.

string[] fruits = { "apple", "passionfruit", "banana", "mango",
                      "orange", "blueberry", "grape", "strawberry" };
   
IEnumerable<string> query =
    fruits.TakeWhile((fruit, index) => fruit.Length >= index);
   
foreach (string fruit in query)
{
    Console.WriteLine(fruit);
}
   
/*
 This code produces the following output:

 apple
 passionfruit
 banana
 mango
 orange
 blueberry
*/
Question: Given an array of numbers, find if ALL numbers are a multiple of a provided number. For example, all of the following numbers - 30, 27, 15, 90, 99, 42, 75 are multiples of 3.
The trick here is to use the Enumerable.All<TSource> method which determines whether all elements of a sequence satisfy a condition.
static void Main(string[] args)
{
    int[] numbers = { 30, 27, 15, 90, 99, 42, 75 };

    bool isMultiple = MultipleTester(numbers, 3);
}

private static bool MultipleTester(int[] numbers, int divisor)
{
    bool isMultiple =
        numbers.All(number => number % divisor == 0);
   
    return isMultiple;
}



Question: Given an array of numbers, find if ANY of the number is divisible by 5. For example, one of the following numbers - 30, 27, 18, 92, 99, 42, 72 is divisible by 5.

Again, the key fact here is to use Enumerable.Any<TSource> method which determines whether any element of a sequence satisfies a condition. The code is very similar to the ALL case.

static void Main(string[] args)
{
    int[] numbers = { 30, 27, 18, 92, 99, 42, 72 };
       
    bool isDivisible = IsDivisible(numbers, 3);
}

private static bool IsDivisible(int[] numbers, int divisor)
{
    bool isDivisible =
        numbers.Any(number => number % divisor == 0);
   
    return isDivisible;
}


Another way to present a similar question that utilizes Enumerable.Any<TSource> method is shown below.
Question: Given a GPSManufacturer and GPSDevice data structure as defined below, find all the manufacturers that have at least 1 or more active GPS devices.
class GpsDevice
{
    public string Name;
    public bool IsActive;
}
   
class GpsManufacturer
{
    public string Name;
    public GpsDevice[] Devices;
}
   
static List<GpsManufacturer> gpsManufacturers =
    new List<GpsManufacturer>
    {
        new GpsManufacturer
           {Name = "manf1",
            Devices = new GpsDevice[]
            {
                new GpsDevice {Name = "device1", IsActive = true},
                new GpsDevice {Name = "device2", IsActive = false}
            }
        },
        new GpsManufacturer
           {Name = "manf2",
            Devices = new GpsDevice[]
            {
                new GpsDevice {Name = "device1", IsActive = false},
                new GpsDevice {Name = "device2", IsActive = false}
            }
        },
        new GpsManufacturer
        {Name = "manf3"}
    };



The following function finds out the active GPS manufacturers.

        public static void ActiveGpsManufacturers()
        {
            // Determine which manufacturers have a active device.
            IEnumerable<string> activeManf =
                from manf in gpsManufacturers // for all manufacturers
                where manf.Devices != null && // they have a list of devices
                    // and at least one of the device is active
                      manf.Devices.Any(m => m.IsActive == true)
                select manf.Name; // select them
               
            // just for debugging
            foreach (string name in activeManf)
                Console.WriteLine(name);
        }



As an extension question and using Lambda expressions, consider the following question:
Question: Find the count of all the manufacturers that have at least 1 or more active GPS devices.


public static void ActiveGpsManufacturersCount()
{
    // to count the number of active manufacturers
    int activeManfCount =
        gpsManufacturers.Count
            (manf => (manf.Devices != null &&
                      manf.Devices.Any(m => m.IsActive == true)));

    // debugging
    Console.WriteLine("Active Manf count: {0}", activeManfCount);
}
MSDN has extensive documentation on LINQ. I recommend reading about the various functions and then trying out various queries on your own. LINQPad is an excellent tool to learn also.
Question: Given a sentence, group the words of same length, sort the groups in increasing order and display the groups, the word count and the words.
For example, the following sentence: “LINQ can be used to group words and count them too” should result in an output like:
Words of length: 2, Count: 2
be
to
Words of length: 3, Count: 3
can
and
too
Words of length: 4, Count: 3
LINQ
used
them
Words of length: 5, Count: 3
group
words
count
Let’s look at the code. The function to do solve this is quite simple. I have commented the code to highlight the LINQ operations that parse the sentence and converts it into relevant solution.
static void Main(string[] args)
{
    SentenceParsing("LINQ can be used to group words and count them too");
}

public static void SentenceParsing(string sentence)
{
    // Split the string into individual words to create a collection.
    string[] words = sentence.Split(' ');
   
    // LINQ query
    var query =
        from w in words // for all the words
        group w by w.Length into grp // group them by length
        orderby grp.Key // order by length
        select new
        { // create a new object with the required props
            Length = grp.Key,
            Words = grp,
            WordCount = grp.Count()
        };
           
    // execute the query
    foreach (var obj in query)
    {
        Console.WriteLine("Words of length: {0}, Count: {1}",
            obj.Length, obj.WordCount);
        foreach (string word in obj.Words)
            Console.WriteLine(word);
    }
}
LINQ Query, Selection, Partial Selections and Aggregations
LINQ allows you to write structured, type-safe queries over local object collections and remote data sources. LINQ interview questions are short and allow the interviewer to quickly test the depth of your knowledge in LINQ and to a certain degree, extension methods.
Let’s review a bunch of small functions that show you a few LINQ operations.
The example below shows you how to use the Where and Select LINQ extensions:
public static void LinqQueryAndSelection()
{
    List<string> fruits = new List<string>
                    { "apple", "passionfruit", "banana", "mango",
                      "orange", "blueberry", "grape", "strawberry" };
       
    // find all fruits that have names of length 5 or less
    IEnumerable<string> query1 = fruits.Where(fruit => fruit.Length < 6);
       
    foreach (string fruit in query1)
        Console.WriteLine(fruit);
       
    // convert the names of all the fruits to uppercase
    IEnumerable<string> query2 = fruits.Select(n => n.ToUpper());
       
    foreach (string fruit in query2)
        Console.WriteLine(fruit);
}


This next example shows you how to do partial selections:

public static void LinqPartialSelection()
{
    List<string> fruits = new List<string>
                    { "apple", "passionfruit", "banana", "mango",
                      "orange", "blueberry", "grape", "strawberry" };
       
    // find first 3 fruits
    IEnumerable<string> query1 = fruits.Take(3);
       
    foreach (string fruit in query1)
        Console.WriteLine(fruit);
       
    // skip the first 3 fruits
    IEnumerable<string> query2 = fruits.Skip(3);
       
    foreach (string fruit in query2)
        Console.WriteLine(fruit);
       
    // single element operations
    string firstFruit = fruits.First(); // apple
    string lastFruit = fruits.Last(); //  strawberry
    string thirdFruit = fruits.ElementAt(2); // banana
    string fruitStratingWithM = fruits.First(f => f.StartsWith("m")); // mango
}


This last example shows you how to use LINQ to aggregate values:

public static void LinqAggregation()
{
    int[] numbers = { 3, 4, 5, 6, 7, 8 };
       
    // aggregation operations
    int count = numbers.Count(); // 6
    int min = numbers.Min(); // 3
    int max = numbers.Max(); // 8
    double average = numbers.Average(); // 5.5
       
    // the operators above also take an optional predicate
    int countEvensOnly = numbers.Count(n => n % 2 == 0);
       
    // assume that values decay over period
    // MAX and MIN functions allow the numbers to be transformed
    // before the operation
    int maxAfterMultiplicationByTwo = numbers.Max(n => n * 2); // 16
}


There is much more to LINQ than these starter examples. From an interviewing perspective you should learn in depth about the standard Query operations which can be broken down into several categories:


Filtering operations: Where, Take, Skip, etc.
Project operations: Select, Join, etc.
Ordering operations: OrderBy, ThenBy, Reverse. etc.
Grouping operations: GroupBy
Set operations: Concat, Union, etc.
Element operations: First, FirstOrDefault, Last, etc.
Aggregation operations: Count, Min, Max, Sum, etc.
Qualifier operations: Contains, Any, All, etc.
Conversion operations: ToArray, ToList, Cast, etc.

Another important fact to note is that LINQ operations can be chained as shown in the example below.

public static void LinqChaining()
{
    List<string> fruits = new List<string>
                    { "apple", "passionfruit", "banana", "mango",
                      "orange", "blueberry", "grape", "strawberry" };
       
    // operator chaining
    IEnumerable<string> query1 = fruits
                            .Where(f => f.Contains("a"))
                            .OrderBy(f => f.Length)
                            .Select(f => f.ToUpper());
       
    foreach (string fruit in query1)
        Console.WriteLine(fruit);
}
1.What is Language Integrated Query (LINQ)?
LINQ is a set of extensions to .NET Framework that encapsulate language integrated query, set and other transformation operations..................
Read answer
2.Difference between LINQ and Stored Procedures.
Difference between LINQ and Stored Procedures: 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...............
Read answer
3.Pros and cons of LINQ (Language-Integrated Query)
Pros of LINQ: Supports type safety, Supports abstraction and hence allows developers to extend features such as multi threading.............
Read answer
4.Disadvantages of LINQ over Stored Procedures
Disadvantages of LINQ over stored procedures: LINQ needs to process the complete query, which might have a performance impact in case of complex queries against stored procedures which only need serialize sproc-name and argument data over the network.............
Read answer
5.Can I use LINQ with databases other than SQL Server? Explain how
LINQ supports Objects, XML, SQL, Datasets and entities. One can use LINQ with other databases through LINQ to Objects or LINQ to Datasets, where the objects...............
Read answer
6.What is Linq to SQL Deferred Loading?
7. Write a Program using Skip and Take operators. How can it beneficial for bulky data accessing on page?
8. Write a Program for Concat to create one sequence of Data Rows that contains DataTables's Data Rows, one after the other.
9. How can you find average of student marks from student tables (Columns are StudentID, Marks)?
10. What is Lambda Expressions? How can we optimize our linq code using this Expression?
11. What is “OfType” in linq?
12. How can we find that Sequence of Items in two different array (same Type) in the same order using linq query?
13. Differentiate between Conversion Operator “IEnumerable” and “ToDictionary” of linq.
14. Why is Linq beneficial than Store Procedure?
15. List out the Data Context Functions. Where do we use “SubmitChanges()”?
16. Why do we use “Contains” method for strings type functions?
17. Partition following list of numbers by their remainder when divided by “3”-
{
Var numbers() = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
}
18. Can you Concat two arrays to create one sequence that contains each array's values, one after the other?
19. Write a small Program to generate Xml Document from table like (StudentRecord Table) using linq query.
20. What is Quantifiers in reference linq to Dataset?
1) What is the DataContext class and how is it related to LINQ?
When we add a LINQ to SQL Classes item to our application and open the O/R Designer, then a blank surface appears which is called DataContext class.
The DataContext class is a LINQ to SQL class that is a bridge between a SQL Server database and the LINQ to SQL entity classes.
DataContext class has all the information of the connection with the database and the methods to manipulate the data in database.
It is configured with connection information provided by the first item that is dragged onto the design surface.
2) How does LINQ to SQL differ from Entity framework?
LINQ to SQL is suggested to use for fast development using SQL Server. Entity Framework is for enterprise level application and supports SQL server and other databases too.
LINQ to SQL classes maps one entity class with one database table. Entity Framework supports conceptual model which maps to storage model via mappings.
One Entity Framework class can be mapped to multiple tables or one table can be mapped to multiple classes.
LINQ is mainly targeted on rapid development whereas Entity Framework is for enterprise scenarios where the requirement is to create loosely coupled framework.
3) Give example of get data from a table in LINQ to SQL.
We can fetch the data from database table by simply writing a LINQ query and then running that query to retrieve the data.
LINQ to SQL will convert all the LINQ operation to the appropriate SQL operations that we are familiar with.
In the following example, the Names of employees from Mumbai are retrieved and shown in the console window.
// EmployeeDataContenxt inherits from System.Data.Linq.DataContext.
EmployeeDataContenxt db = new EmployeeDataContenxt();

var EmployeeNames =
from emp in db.Employee
where emp.City == "Mumbai"
select emp.EmpName;

foreach (var employee in EmployeeNames)
{
Console.WriteLine(employee);
}
4) Give an example of Insert operation in LINQ to SQL.
For insertion of data in database we need to give values of each field to the entity class’s object and then we have to use SubmitChanges method on the DataContext.
In the following example, a new Employee and his details are inserted to the Employee table by using InsertOnSubmit.
For example
// EmployeeDataContenxt inherits from System.Data.Linq.DataContext.
EmployeeDataContenxt db = new EmployeeDataContenxt();
Employee emp = new Employee();
emp.EmpName = "Arpit Jain";
emp.City = "Mumbai";
emp.EmployeeID = "123";
emp.Phone = "555-555-5555";
db.Employee.InsertOnSubmit(emp); // The new Employee object is added in the object model.
// In LINQ to SQL, the details will not be inserted in the database until
// SubmitChanges is executed.
db.SubmitChanges();
5) How to Update data in LINQ to SQL? Give example.
For Updation of data in database, first we need to get the item and update it in the object model. After we have changed the object, call SubmitChanges on the DataContext to update the database.
In the following example, Employee with EmployeeID 123 is retrieved. Then the name of the Employee is changed from "Arpit Jain" to "Arpit B. Jain". Finally,SubmitChanges is called to update the changes in the database.
For example
EmployeeDataContenxt db = new EmployeeDataContenxt();

var empData =
from emp in db.Employees
where emp.EmployeeID == 123
select emp;
empData.EmpName = "Arpit B. Jain";
db.SubmitChanges();
6) Give an example of Delete operation in LINQ to SQL.
For Deletion of an item, remove the item from the collection to which it belongs, and then execute SubmitChanges on the DataContext to commit the deletion.
In the following example, the employee who has EmployeeID of 981 is retrieved from the database. Then, after ensuring that theEmployee data was retrieved, DeleteOnSubmit is executed to remove that object from the collection.
At last, SubmitChanges is executed to remove the row from the database.
EmployeeDataContenxt db = new EmployeeDataContenxt();
var deleteEmp =
from emp in db.Employees
where emp.EmployeeID == 981
select emp;

if (deleteEmp.Count() > 0)
{
db.Employees.DeleteOnSubmit(deleteEmp.First());
db.SubmitChanges();
}
7) How to do a WHERE IN clause in LINQ to SQL?
-LINQ has "Contains" which is same as "IN" in SQL but the approach is different. An element isn't "in" a set, a set "contains" an element.
For example
int[] names = { “Arpit”, “Bob”, “Jack” };
var result = from emp in db.Employees
where names.Contains(emp.EmpId)
select emp

-It can also be written in simpler way with a lambda expression.
-int[] names = { “Arpit”, “Bob”, “Jack” };
var result = db.Employees.Where(emp => names.Contains(emp.EmpId));
Linq interview questions for experienced

Linq interview questions for experienced - contributed by Arpit Jain
1) What is PLINQ?
2) Which are the rules apply to a variable scope in lambda expressions?
3) What is the difference between the Select clause and SelectMany() method in LINQ?
4) What are the different implementations of LINQ?
5) Why var keyword is used and when it is the only way to get query result?
6) What are the pros and cons of LINQ (Language-Integrated Query)?
7) What is benefit of using LINQ on Dataset?
8) What is the difference between the Take and Skip clauses?
9) Can you tell the advantages of LINQ over stored procedure?
10) Which are the language extensions in C# 3.0 useful for LINQ?
1) What is PLINQ?
PLINQ stands for Parallel Language Integrated Query.
It supports parallel mechanism of LINQ, which means the query will be executed by multiple processors.
All the LINQ operators are supported by PLINQ as well as query collections by using PLINQ.
It can also execute multiple LINQ queries at a time and makes use of multiple processors of the computer.
PLINQ uses parallelism, which enables fast execution of queries.
2) Which are the rules apply to a variable scope in lambda expressions?
A variable used in lambda expression won’t be garbage-collected until the delegate that references that variable is out of the scope.
Variables used in a lambda expression won’t be accessible in the parent method.
A lambda expression can’t get a ref or out parameter from an containing method.
The return statement used in a lambda expression won’t return for the enclosing method.
A lambda expression does not support a goto, break or continue statement who point t outer the body.
3) What is the difference between the Select clause and SelectMany() method in LINQ?
In both the Select clause and SelectMany() method a result value will be generated out of the source of values.
The difference between both of them is in the result set. The Select clause will generate one value for every source value.
The result value is a collection which is having the same number of elements from the query.
On the other side, theSelectMany() method generates a single result that has a concatenated from the query.
4) What are the different implementations of LINQ?
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.
5) Why var keyword is used and when it is the only way to get query result?
var is a keyword introduced in C# 3.0. It is used to substitute the type of the variable with a generalized keyword.
The compiler infers the actual type from the static type of the expression used to initialise the variable.
It is must to use the var keyword when we deal with the queries which returns anonymous type. E.g.

var results = from t in MyStringData
select new
{
NoOfLetter = t.Length,
CapitalString = t.ToUpper()
};

foreach (var result in results)
{
Console.WriteLine(result.NoOfLetter + " " + result.CapitalString);
}
6) What are the pros and cons of LINQ (Language-Integrated Query)?
Pros of LINQ:
LINQ provides the type safety.
Abstraction is provided by LINQ and thus it enable us to use the concept of multithreading.
LINQ is easy to deploy as well as it is easy to understand.
Using .Net debugger we can debug the LINQ code.
LINQ allow us to use more than more one database together.
Cons of LINQ:
In LINQ, it is necessary to process the whole query, and therefore it reduces the performance when we have large and complex queries.
It is generic, while we can use multiple feature of database using stored procedures.
In the case of any change in queries, we have to recompile and redeploy the assembly.
7) What is benefit of using LINQ on Dataset?
The major objective to use LINQ to Dataset is to execute strongly typed queries over Dataset.
Consider the scenario that you require to merge the results from two Datasets, or you require to take a distinct value from a Dataset, then we can use LINQ.
Usually we can use the SQL queries to execute on the database to get the Dataset, but we can’t use SQL queries on a Dataset to retrieve a single value, for which use ofADO.NET features is necessary.
While, in case of LINQ, it supports better dignified way to execute queries on Dataset and gives some new functionalities than ADO.NET.
8) What is the difference between the Take and Skip clauses?
The Take clause will give you a predefined number of elements.
Suppose if you want to return two elements from an array then you can use Take clause.
The Skip clause will skip the predefined number of elements in the query and returns the remaining elements.
Suppose 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.
9) Can you tell the 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.
10) Which are the language extensions in C# 3.0 useful for LINQ?
Lambda Expressions: If we want to create a delegate in LINQ then we can use a Lambda expression.
Anonymous Types: We can use Anonymous types to generate a bunch of read-only properties in a single object in which it is not necessary to define a type first.
Object Initializers: C# 3.0 supports Object Initializers to create and initialize the objects in s single step.
Implicitly Typed Variables: To achieve this we can use “var” keyword.


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.
1. What is Language Integrated Query (LINQ)?
LINQ is a programming model that is the composition of general-purpose standard query operators that allow you to work with data, regardless of the data source in any .NET based programming language. It is the name given to a set of technologies based on the integration of query capabilities into any .NET language.
2. What are LINQ query expressions?
A LINQ query, also known as a query expression, consists of a combination of query clauses that identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It specifies what information should be retrieved from the data source.
3. Write the basic steps to execute a LINQ query.
The following are the three basic steps to execute a LINQ query:
• Obtain the data source (The data source can be either an SQL database or an XML file)
• Create a query
• Execute the query
4. Write the basic syntax of a LINQ query in Visual Basic as well as in C#.
In Visual Basic, the basic syntax of a LINQ query starts with the From clause and ends with the Select or Group By clause. In addition, you can use the Where, Order By, and Order By Descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.

In C#, the basic syntax of a LINQ query starts with the From clause and ends with the Select or group by clause. In addition, you can use the where, orderby, and Orderby descending clauses to perform additional functions, such as filtering data and generating the data in a specific order.
5. In which statement the LINQ query is executed?
A LINQ query is executed in the For Each statement in Visual Basic and in the foreach statement in C#.
6. In LINQ, lambda expressions underlie many of the standard query operators. Is it True or False?
7. What is PLINQ?
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.
8. What are the different Visual Basic features that support LINQ?
Visual Basic includes the following features that support LINQ:
• Anonymous types - Enables you to create a new type based on a query result.
• Implicitly typed variables - Enables the compiler to infer and assign a type when you declare and initialize a variable.
• Extension method - Enables you to extend an existing type with your own methods without modifying the type itself.
9. What is the function of the DISTINCT clause in a LINQ query?
The DISTINCT clause returns the result set without the duplicate values.
10. What is the DataContext class and how is it related to LINQ?
After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. 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.
11. What is the difference between the Take and Skip clauses?
The Take clause returns a specified number of elements. For example, you can use the Take clause to return two values from an array of numbers. The Skip clause skips the specified number of elements in the query and returns the rest. For example, you can use the Skip clause to skip the first four strings in an array of strings and return the remaining array of string.
12. What is Object Relational Designer (0/R Designer)?
The 0/R Designer provides a visual design surface to create LINQ to SQL entity classes and associations (relationships) that are based on objects in a database.
13. Which interface implements the standard query operators in LINQ?
The standard query operators implement the IEnumerable or the IQueryable interface in C# and theIEnumerable(Of T) or the IQueryable(Of T) interface in Visual Basic.
14. What are standard query operators in LINQ?
The standard query operators in LINQ are the extension methods that form the LINQ pattern. These operators form an API that enables querying of any .NET array or collection. It operates on sequences and allows you to perform operations, such as determining if a value exists in the sequence and performing an aggregated function, such as a summation over a sequence.
15. On what parameter does the GroupBy clause group the data?
The GroupBy clause groups the elements that share a common attribute.
16. What is a LinqDataSource control?
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.
17. How can you open the O/R Designer?
You can open the O/R Designer by adding a new LINQ to SQL Classes item to a project.
18. The standard query operators are themselves a set of extension methods that provide the LINQ query functionality for any type that implements the IEnumerable interface in Visual Basic. Is it True or False?
19. What are lambda expressions in LINQ?
A lambda expression is a function without a name that calculates and returns a single value. All lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.
20. Before you query a DataSet object by using LINQ to DataSet, you must first populate the dataset How can you do this?
You can load the data into the dataset by using different methods, such as:
• Using the DataAdapter class
• Using LINQ to SQL
21. What are the different implementations of LINQ?
The different implementations of LINQ are:
• LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-time infrastructure to manage relational data as objects.
• LINQ to DataSet - Refers to a component that makes it easier and faster to query over data cached in a DataSet object.
• LINQ to XML - Provides an in-memory XML programming interface.
• LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable(T)collection directly, without the use of an intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML.
22. Which command-line tool generates code and mapping for the LINQ to SQL component of .NET Framework?
The SqlMetal.exe command-line tool generates code and map the LINQ to SQL component.
23. Name the control that exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.
The LinqDataSource control exposes the LINQ features to Web developers through the ASP.NET data-source control architecture.
24. What is the difference between the Select clause and SelectMany() method in LINQ?
Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, theSelectMany() method produces a single result that contains a concatenated collection from the query.
There are many areas you can use linq some examples are
You can create/modify/navigate/traverse xml document using linq. You can call it linq to xml.
you can search/sort/navigate/filter custom object hierarchy, object collection, list compare, file content search, directory search etc using linq. You can call it linq to object.
You can use object relational mapping using linq. You can call it linq to sql.
You can access/navigate/filter dataset using linq. You can call it linq to dataset.
In advance you can create linq providers for various component easily access access, create object from read various sources etc.
LINQ can be used anywhere within a C# or Visual Basic .NET program where a variable can be declared.

See the Wikipedia article on LINQ:
LINQ provides the capability to query data to conveniently extract and process data from arrays, enumerable classes, XML documents, relational databases and third-party data sources.
1 :: 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.
Is This Answer Correct?44 Yes 1 No
Post Your Answer
2 :: Why can not datareader by returned from a Web Services Method?
Because, it is not serializable
Is This Answer Correct?33 Yes 0 No
Post Your Answer
3 :: What is the extension of the file, when LINQ to SQL is used?
The extension of the file is .dbml
Is This Answer Correct?28 Yes 0 No
Post Your Answer
4 :: 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!
Is This Answer Correct?19 Yes 0 No
Post Your Answer
5 :: 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.
Is This Answer Correct?11 Yes 0 No
Post Your Answer
6 :: What is the LINQ file extension that interacts with Code Behind objects.
its .dbml
Is This Answer Correct?16 Yes 0 No
Post Your Answer
7 :: 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.
Is This Answer Correct?14 Yes 0 No
Post Your Answer
8 :: Difference between LINQ and 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!
4. PreCompiled - Stored Procedures are precompiled, and LINQ queries need to compile before execution. So stored procedures are fast in performance.
Is This Answer Correct?11 Yes 0 No
Post Your Answer
9 :: What are Benefits and Advantages of LINQ?
Benefits and Advantages of LINQ are:
1. Makes it easier to transform data into objects.
2. A common syntax for all data.
3. Strongly typed code.
4. Provider integration.
5. Reduction in work.
6. Performance in the general case doesn't become an issue.
7. Built-in security.
8. LINQ is declarative.
Is This Answer Correct?8 Yes 0 No
Post Your Answer
10 :: What are the three main components of LINQ or Language INtegrated Query?
1. Standard Query Operators
2. Language Extensions
3. LINQ Providers
Is This Answer Correct?9 Yes 0 No
Post Your Answer
11 :: How are Standard Query Operators implemented in LINQ?
Standard Query Operators are implemented as extension methods in .NET Framework. These Standard Query Operators can be used to work with any collection of objects that implements the IEnumerable interface. A class that inherits from the IEnumerable<t> interface must provide an enumerator for iterating over a collection of a specific type. All arrays implement IEnumerable<t>. Also, most of the generic collection classes implement IEnumerable<t> interface.
Is This Answer Correct?7 Yes 0 No
Post Your Answer
12 :: 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 and more.
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
Is This Answer Correct?5 Yes 0 No
Post Your Answer
13 :: List the important language extensions made in C# to make LINQ a reality?
1. Implicitly Typed Variables
2. Anonymous Types
3. Object Initializers
4. Lambda Expressions
Is This Answer Correct?4 Yes 0 No
Post Your Answer
14 :: 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 that executes an equivalent query against a specific data source.
Is This Answer Correct?2 Yes 0 No
Post Your Answer
15 :: What are the four LINQ Providers that .NET Framework ships?
1. LINQ to Objects - Executes a LINQ query against a collection of objects
2. LINQ to XML - Executes an XPATH query against XML documents
3. LINQ to SQL - Executes LINQ queries against Microsoft SQL Server.
4. LINQ to DataSets - Executes LINQ queries against ADO.NET DataSets.
Is This Answer Correct?6 Yes 1 No
Post Your Answer
16 :: Write a program using LINQ to find the sum of first 5 prime numbers?
class Program
{
static void Main()
{
int[] MyPrimeNumbers = {1,2,3,5,7};
// Use the Count() and Sum() Standard Query Operators to
// compute the count and total sum respectively
Concole.WriteLine("The sum of first {0} prime number is {1}",
MyPrimeNumbers.Count(), MyPrimeNumbers.Sum());
}
}
Is This Answer Correct?3 Yes 0 No
Post Your Answer
17 :: What is 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"),
)
);
Is This Answer Correct?4 Yes 0 No
Post Your Answer
18 :: 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.
Is This Answer Correct?4 Yes 0 No
Post Your Answer
19 :: 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.
Is This Answer Correct?1 Yes 0 No
Post Your Answer
20 :: Which classs extension methods are used in LINQ to SQL?
1. System.Linq.Enumerable
2. System.Linq.Queryable
3. None of these
Is This Answer Correct?9 Yes 0 No
Post Your Answer
21 :: Which assembly represents the core LINQ API?
System.Query.dll assembly represents the core LINQ API.
Is This Answer Correct?3 Yes 0 No
Post Your Answer
22 :: What is the use of System.Data.DLinq.dll?
System.Data.DLinq.dll provides functionality to work with LINQ to SQL.
Is This Answer Correct?1 Yes 0 No
Post Your Answer
23 :: What is the use of System.XML.XLinq.dll?
System.XML.XLinq.dll contains classes to provide functionality to use LINQ with XML.
Is This Answer Correct?1 Yes 0 No
Post Your Answer
24 :: Why cant datareader be returned from a Web Services Method?
Because datareader is not serializable.
Is This Answer Correct?2 Yes 0 No
Post Your Answer
25 :: What is the LINQ file extension that interacts with Code Behinds objects?
The extension of the file is .dbml
Is This Answer Correct?1 Yes 0 No
Post Your Answer
26 :: What is Linq to SQL Deferred Loading?
(C#) - Deferred Loading is a property of Linq to sql, by default it is set true,
Example – Let’s have two tables -
Blogs Table (BlogID ,Blog Name,owner) and Post table ( PostID, BlogID, Title, Body)
To find Name and No’s of posts in each blog:

BlogDataContext ctx = new BlogDataContext( );
var query = from b in ctx.Blogs select b;
foreach (Blog b in query)
{
Console.WriteLine("{0} has {1} posts", b.BlogName,
b.Posts.Count);
}


Output of queries Produce Blog name with no’s of post, But For each Blog Looping will be occurs (in case long list of blogs) that’s reduces Overall Performance that’s called the Deferred loading.
Is This Answer Correct?1 Yes 0 No
Post Your Answer
27 :: Write a Program using Skip and Take operators. How can it beneficial for bulky data accessing on page?
“skip” and “take” Operator used for Paging. Suppose we have Customer table of 100 records. To find 10 records by skipping the first 50 records from customer table-

Public void Pagingdatasource ()
{
Var Query = from CusDetails in db.customer skip (50) Take (10)
ObjectDumper.Write(q)
}


Hence The LinQ “ SKIP” operator lets you skip the results you want, and “Take” Operator enables you yo select the rest of result . So By Using Skip and Take Operator, You can create paging of Specific sequence.
Is This Answer Correct?1 Yes 0 No
Post Your Answer
28 :: Write a Program for Concat to create one sequence of Data Rows that contains DataTabless Data Rows, one after the other?
(C#)

Public void Datasetlinq()
{
var numbersA = TestDS.Tables("NumbersA").AsEnumerable();
var numbersB = TestDS.Tables("NumbersB").AsEnumerable();
var allNumbers = numbersA.Concat(numbersB);
Console.WriteLine("All numbers from both arrays:");
foreach (object n_loopVariable in allNumbers)
{
n = n_loopVariable;
Console.WriteLine(n["number"]);
}
}
Is This Answer Correct?1 Yes 0 No
Post Your Answer
29 :: How can you find average of student marks from student tables (Columns are StudentID, Marks)?
(C#)

Public void LinqToSqlAverage()
{
var query = (from p in db. student. Marks).Average();
Console.WriteLine(q);
}
Is This Answer Correct?1 Yes 0 No
Post Your Answer
30 :: What is “OfType” in linq?
public void TypeofExa()
{
Var numbers = {null,1.0,"two", 3,"four",5,"six",7.0 };
var doubles = from n in numbers where n is doublen;
Console.WriteLine("Numbers stored as doubles:");
foreach (object d in doubles)
{
Console.WriteLine(d);
}
}


Output:
Numbers stored as doubles:
1
7
Is This Answer Correct?1 Yes 1 No
Post Your Answer
31 :: How can we find Sequence of Items in two different array (same Type) in the same order using linq query?
Public void MatchSequenceLinq()
{
Var wordsA = {"Rahul","ashok","sweta"};
Var wordsB = {"rahul","ashok","sweta"};
var match = wordsA.SequenceEqual(wordsB);
Console.WriteLine("The sequences match: {0}", match);
}
Is This Answer Correct?2 Yes 0 No
Post Your Answer
32 :: Differentiate between Conversion Operator “IEnumerable” and “ToDictionary” of LINQ?
IEnumerable and To Dictionary both are Conversion Operator which are used to solved to conversion type Problems.
“AsEnumerable ” operator simply returns the source sequence as an object of type IEnumerable. This kind of “conversion on the fly” makes it possible to call the general-purpose extension methods over source, even if its type has specific implementations of them
Signature:

public static IEnumerable<T> AsEnumerable<T>
(
this IEnumerable<T> source
);


“ToDictionary ” Conversion Operator is the instance of Dictionary (k,T) . The “keySelector ”predicate identifies the key of each item while “elementSelector ”, if provided, is used to extract each single item.
Key and elementSelector Predicate can be Used in following ways-
Example-

Public void ToDictionatyExample()
{
Var scoreRecords=
{
new {Name = "Alice",Score = 50 },
new {Name = "Bob",Score = 40 },
new {Name = "Cathy", Score = 45}
};
Var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
Console.WriteLine("Bob's score: {0}", scoreRecordsDict("Bob"));
}


Result: Bob's score: { Name = Bob, Score = 40 }
Is This Answer Correct?2 Yes 0 No
Post Your Answer
33 :: List out the Data Context Functions. Where do we use “SubmitChanges()”?
Create Database ()
Delete database ()
Database Exist ()
Submit Changes ()
Create Query()
Log()
SubmitChanges() - SunbmitChanges Data Context Fuction Used to submit any update to the actual database.
Is This Answer Correct?1 Yes 0 No
Post Your Answer
34 :: Why do we use “Contains” method for strings type functions?
Contains method Used to find all matching records From Given string using Matching keywords.
Example-
This Examples returns the Customer Names from Customer tables whose Names have contains “Anders”

Public void LinqToSqlStringUsingContains()
{
Var q = From c In db.Customers _
Where c.ContactName.Contains("Anders") _
Select c
ObjectDumper.Write(q)
}
Is This Answer Correct?2 Yes 0 No
Post Your Answer
35 :: What is Quantifiers in reference linq to Dataset?
Quantifier Operators return the Boolean value (either True or false) if some or all the elements in a sequence satisfy a condition,
Mainly two Quantifiers in linq:

Any
All

Examples (vb)

"Any" to determine if any of the words in the array contain the substring

Public Sub ExampleAny()
Dim words() = {"believe", "relief", "receipt", "field"}
Dim iAfterE = words.Any(Function(w) w.Contains("ei"))
Console.WriteLine("There is a word that contains in the
list that contains 'ei': {0}", iAfterE)
End Sub


Result:
There is a word that contains in the list that contains 'ei': True

"All" to return a grouped a list of products only for categories that have all of their products in stock

Public Sub Quantifier_All_Exam()
Dim products = GetProductList()
Dim productGroups = From p In products _
Group p By p.Category Into Group _
Where (Group.All(Function(p) p.UnitsInStock > 0)) _
Select Category, ProductGroup = Group
ObjectDumper.Write(productGroups, 1)
End Sub
Is This Answer Correct?3 Yes 0 No
Post Your Answer

No comments:

Post a Comment