1. 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.
2. 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
3. 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.
4. 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#.
5. What is the function of the DISTINCT clause in a LINQ query?
The DISTINCT clause returns the result set without the duplicate values.
6. 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.
7. 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.
8. On what parameter does the GroupBy clause group the data?
The GroupBy clause groups the elements that share a common attribute.
9. 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.
10. 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.
11. 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#.
12. 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.
13. 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
14. 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.
15. 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.
16. 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.
17. 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.
18. 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.
19. Difference in IEnumerable and IQueryable?
The major difference is that IEnumerable will enumerate all elements, while IQueryable will enumerate elements based on query only. Let's may be you have asked for 1 record only by saying emplist.Take(1); In this case IEnumerable will iterate all elements but IQueryable will use Top 1 as a clause to fire a query.
When using IQueryable, the LINQ query gets used by IQueryProvider. This must be interpreted or compiled in order to get the result. This mean the delegate it receives is an expression tree instead of a method to invoke.
IEnumerable is great for working with in-memory collections, but IQueryable<t> allows for a remote data source, like a database or web service.
First thing linq is not a class. It's a namespace. There are different members which are included in System.Linq namespace like Enumerable, Querable, Lookup<>
20. Difference in AsEnumerable() vs AsiQueryable() Linq?
Enumerate means it will loop through the collection. This mean IEnumerable will loop thourgh all elements where as IQueryable will loop based on condition only.
Expression trees represent code in a tree-like data structure, where each node is an expression. So it will execute tree structured expression instead of invking the function.
21. Difference Between First() and FirstOrDefault() in LINQ?
A. First()
When we Use First() in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Expression in Where Clause then It Will Throw You Exception as:InvalidOperationException: Sequence contains no elements.
When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().
First() returns First Element Of Sequence.
First() throws Exception when There IS No element Presnt In Table.
B. FirstORDefault():
1. When we Use FirstORDefault () in LINQ in Query Syntax Or Method Syntax, At that Time If we Do not Get any Record Corresponding To Criteria in Where Clause then It Will return Some Default Value (Null).
2. When There Are Multiple Records Releted To TO Matching Expression and If You want only the First One Then You can Use First().
FirstOrDefault () returns First Element Of Sequence.
FirstOrDefault () does not throws Exception when There IS No element Present in Table.
22. Understanding Single, SingleOrDefault, First and FirstOrDefault?
Single
It returns a single specific element from a collection of elements if element match found. An exception is thrown, if none or more than one match found for that element in the collection.
SingleOrDefault
It returns a single specific element from a collection of elements if element match found. An exception is thrown, if more than one match found for that element in the collection. A default value is returned, if no match is found for that element in the collection.
First
It returns first specific element from a collection of elements if one or more than one match found for that element. An exception is thrown, if no match is found for that element in the collection.
FirstOrDefault
It returns first specific element from a collection of elements if one or more than one match found for that element. A default value is returned, if no match is found for that element in the collection.
When to use Single, SingleOrDefault, First and FirstOrDefault
- You should take care of following points while choosing Single, SingleOrDefault, First and FirstOrDefault:
- When you want an exception to be thrown if the result set contains many records, use Single or SingleOrDefault.
- When you want a default value is returned if the result set contains no record, use SingleOrDefault.
- When you always want one record no matter what the result set contains, use First or FirstOrDefault.
- When you want a default value if the result set contains no record, use FirstOrDefault.
Perfomance of SingleOrDefault and FirstOrDefault
FirstOrDefault usually perform faster as compared SingleOrDefault, since these iterate the collection until they find the first match. While SingleOrDefault iterate the whole collection to find one single match.
23. Difference between iEnumerable and iEnumerator in c# .net?
Ans : We will discuss here what is IEnumerable, IEnumerator, what are differences between them, where should we use IEnumerable and where to IEnumerator, once we will finish our discussion it will be clear, which one would be best for which situation and why, so let’s see it with example
To better understand we will create a list of age
List<int> ages = new List<int>();
ages.Add(10);
ages.Add(20);
ages.Add(30);
ages.Add(40);
ages.Add(50);
Now convert this list to IEnumerable
IEnumerable<int> age_IEnumerable = (IEnumerable<int>)ages;
foreach (int age in age_IEnumerable)
{
Console.WriteLine(age);
}
There is nothing new, we used foreach here very straight forward, now let’s convert the ages into IEnumerator, there is a method GetEnumerator to convert a list into IEnumerator
IEnumerator<int> age_IEnumerator = ages.GetEnumerator();
while (age_IEnumerator.MoveNext())
{
Console.WriteLine(age_IEnumerator.Current);
}
As you can see here we used while rather than foreach because foreach cannot be used with IEnumerator, but still there is nothing which can suggest us when should we use IEnumerable and where to IEnumerator.
Before we go further, we should know, IEnumerable uses IEnumerator internally also have a function GetEnumerator to convert into IEnumerator, we should use IEnumerable because it make coding easier and clearer as we can see in above example.
Now let’s discuss the main difference, IEnumerable doesn’t remember the state, which row or record it is iterating while IEnumerator remember it and we are going to see this with example by creating method PrintUpto30 and PrintGreaterThan30
Let’s first check with IEnumerator
public void PrintAgeUpto30(IEnumerator<int> age_IEnumerator)
{
while (age_IEnumerator.MoveNext()){
Console.WriteLine(age_IEnumerator.Current);
if (age_IEnumerator.Current > 20) {
Console.WriteLine("PrintGreaterThan30 is called");
PrintGreaterThan30(age_IEnumerator);
}
}
}
public void PrintGreaterThan30(IEnumerator<int> age_IEnumerator)
{
while (age_IEnumerator.MoveNext())
Console.WriteLine(age_IEnumerator.Current);
}
// Now Call PrintUpto30 which will call PrintGreaterThan30
// by using our previous age IEnumerator
PrintUpto30(IEnumerator);
As we know IEnumerator persists state so once we will call PrintGreaterThan30 by passing age_IEnumerator it will print the remaining list, here is the output:
10
20
30
PrintGreaterThan30 is called
40
50
Now let’s check same code with IEnumerable
public void PrintUpto30(IEnumerable<int> age_IEnumerable)
{
foreach (int age in age_IEnumerable){
Console.WriteLine(age);
if (age > 20){
Console.WriteLine("PrintGreaterThan30 is called");
PrintGreaterThan30(age_IEnumerable);
}
}
}
public void PrintGreaterThan30(IEnumerable<int> age_IEnumerable)
{
foreach (int age in age_IEnumerable)
Console.WriteLine(age);
}
// Now Call PrintUpto30 by using our variable age_IEnumerable
PrintAgeUpto30(age_IEnumerable);
Now check the output you will see “PrintGreaterThan30 is called” many times something like this
10
20
30
PrintGreaterThan30 is called
10
....
50
40
PrintGreaterThan30 is called
10
...
50
50
PrintGreaterThan30 is called
10
50
Conclusion:
Both are interface
IEnumerable code are clear and can be used in foreach loop
IEnumerator use While, MoveNext, current to get current record
IEnumerable doesn’t remember state
IEnumerator persists state means which row it is reading
IEnumerator cannot be used in foreach loop
IEnumerable defines one method GetEnumerator which returns an IEnumerator
IEnumerator allows readonly access to a collection
24. What is difference between .edmx and .dbml file in linq?
edmx is the modeling file for Entity Framework.
dbml is the modeling file for Linq 2 Sql.
25. Join in linq C#?
var query =
from department in departments
join employee in employees
on department.ID equals employee.DepartmentID
select new { employee.Name, Department = department.Name };
26. Left Outer Join and Right Outer Join in LINQ
//Left join
var Ljoin = from emp in ListOfEmployees
join proj in ListOfProject
on emp.ProjectID equals proj.ProjectID into JoinedEmpDept
from proj in JoinedEmpDept.DefaultIfEmpty()
select new
{
EmployeeName = emp.Name,
ProjectName = proj != null ? proj.ProjectName : null
};
//Right outer join
var RJoin = from proj in ListOfProject
join employee in ListOfEmployees
on proj.ProjectID equals employee.ProjectID into joinDeptEmp
from employee in joinDeptEmp.DefaultIfEmpty()
select new
{
EmployeeName = employee != null ? employee.Name : null,
ProjectName = proj.ProjectName
};
Perform Left Outer Joins in LINQ?
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };
foreach (var v in query)
{
Console.WriteLine("{0,-15}{1}", v.FirstName + ":", v.PetName);
}
OR
var query =
from u in Repo.T_Benutzer
join bg in Repo.T_Benutzer_Benutzergruppen
on u.BE_ID equals bg.BEBG_BE
into temp
from j in temp.DefaultIfEmpty()
select new
{
BE_User = u.BE_User,
BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG
//, bg.Name
}
Simple Join
var query =
from post in database.Posts
join meta in database.Post_Metas on post.ID equals meta.Post_ID
where post.ID == id
select new { Post = post, Meta = meta };
No comments:
Post a Comment