LINQ Interview Questions & Answers - By Shailendra Chauhan



Comments



Description

Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695 LINQ Interview Questions and Answers All rights reserved. No part of this book can be reproduced or stored in any retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, uploading on server and scanning without the prior written permission of the author. The author of this book has tried his best to ensure the accuracy of the information described in this book. However, the author cannot guarantee the accuracy of the information contained in this book. The author will not be liable for any damages, incidental or consequential caused directly or indirectly by this book. Further, readers should be aware that the websites or reference links listed in this book may have changed or disappeared between when this book was written and when it is read. All other trademarks referred to in this book are the property of their respective owners. www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 1 Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Dedication My mother Mrs. Vriksha Devi and my wife Reshu Chauhan deserve to have theirs name on the cover as much as I do for all theirs support made this possible. I would like to say thanks to all my family members Virendra Singh(father), Jaishree and Jyoti(sisters), Saksham and Pranay(sons), friends, to you and to readers or followers of my blog www.dotnet-tricks.com to encourage me to write this book. I would like to give a special thanks to Kanishk Puri and Avadhesh Sengar for actively participating in the feedback and contributions for this book via theirs valuable feedback and suggestions. -Shailendra Chauhan www.dotnet-tricks.com Handy Tricks For Beginners & Professionals 2 the next question is who this book is for? This book covers useful Interview Questions and Answers on LINQ. one should have a depth knowledge over the subject is going to write.aspx. So.NET. This book is not only the LINQ interview book but it is more than that. LINQ. I hope you will enjoy this book and find it useful. So. That’s what it’s all about. consultant. Entity Framework. My inspiration and knowledge has also come from many years of my working experience and research over it. tricks and tutorials.dotnet-tricks.com and be the part of the discussion. what where my qualification to write this book? My qualification and inspiration come from my enthusiasm for and the experience with the technology and from my analytic and initiative nature.dotnet-tricks. To get the latest information on LINQ. I encourage you to follow the MSDN at http://msdn. C#. ASP.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Introduction Writing a book has never been an easy task. Also. patience and consistency with strong determination to complete it.com that contains . jQuery and many more tips. I have through knowledge and understandings of .dotnet-tricks.microsoft.NET technologies. At the same time I also encourage you to become a continue reader of the blog www. software engineer. It takes a great effort. All the best for your interview and happy programming! www. This book is appropriate for novice as well as for senior level professionals who wants to strengthen their skills before appearing for an interview on LINQ. But most importantly practice a lot and enjoy the technology.Join our . Being a sr.com Handy Tricks For Beginners & Professionals 3 . blogger and author.NET MVC. This book helps you to get the depth knowledge of LINQ with a simple and elegant way. This book is updated to latest version of LINQ. I also encourage you to subscribe to my blog at www.com/enus/library/bb397926. This book is equally helpful to sharpen their programming skills and understanding LINQ in a short time. LINQ.NET MVC. Backbone. founder and chief editor of www. Entity Framework.NET MVC 4 Mobile App Development.NET technologies worldwide and is listed as a non-Microsoft resource in The Microsoft Official community Site. A number of articles of him has become articles-of-the-day. PhoneGap and many more web technologies. jQuery.com and www.NET technologies. jQuery UI.com Handy Tricks For Beginners & Professionals 4 . He loves to work with web applications.dotnet-tricks.dotnetinterviewtricks.com. WCF.NET. He always keeps up with new technologies and learning new skills that allow him to provide better solutions to problems.js. He strives to be the best he can be. ASP.js. www.NET MVC Interview Questions and Answers and LINQ Interview Questions and Answers.NET Consultant. WEB API. selected in dailycommunity-spotlight. His blog www. Windows Azure. He is a technical reviewer of book ASP. Blogger. Author. He is an author He likes to share his working experience.and knowledge through his well-known blogs. SQL Server.Join our . ASP.NET Site. and listed in Recommended Resources for MVC section in The Official Microsoft ASP.dotnet-tricks.dotnet-tricks. jQuery Mobile.com is a well-known knowledge and support resource in the field of .NET Training Programs in Delhi/Noida Call Us : +91-9871749695 About the author Shailendra Chauhan Works as Sr. Mobile apps and Mobile websites using Microsoft technology including C#. research of books ASP. Software Engineer at reputed MNC and has more than 5 years of hand over Microsoft . Knockout. He is a . [email protected]@dotnet-tricks.com Handy Tricks For Beginners & Professionals 5 .Join our .com I am always happy to hear from my readers.com at facebook. Please provide with your valuable feedback and comments! You can also follow www.com pro.dotnet-tricks. linkedin and google plus or subscribe to RSS feed. twitter. or you find an error in the book please drop a line via e-mail.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 How to contact the author Although the author of this book has tried to make this book as accurate as it possible but if there is something strikes you as odd. www. The author e-mail addresses are listed as follows:   pro. .................................................................... 13 Q10.......................................... 17 Q17........................... What is LINQ and why to use it? ...........9 Q6... What are conversion operators? ........................ 16 Q16.................................................................................................................................................................................. What are advantages of using LINQ on DataSet? ... What are element operators? ...... 2 Introduction .................. Which one is fast between SingleOrDefault and FirstOrDefault? ............................ What are different types of operators in LINQ?. What is lambda expression?..................................... What is LINQPad? .......................................................... First and FirstOrDefault?................................ What is anonymous method? ................................ 4 How to contact the author............. 17 Q18.................... 5 LINQ ... 19 Q22.......................................... 3 About the author ............... What is difference among Single................................................................ 16 Q13...................................................NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Table of Contents LINQ Interview Questions and Answers ........ What is LINQ Insight? .............................. 19 www................................................ Which namespace is necessary to use LINQ?................................................. 19 Q23......................................................................................................................................................................................................dotnet-tricks...................................................................................................................................................Join our . What is Extension method?... When to use Single..... What LINQ providers are supported by LINQPad? .................................................................................................................. First and FirstOrDefault? .............. What are different flavors of LINQ? ................ SingleOrDefault.............................................................................................................................................. SingleOrDefault.................. 14 Q11... 16 Q15.......................................................................... How var type is different from anonymous type? ...............................................8 Q4................................................................. 17 Q19...................................................................................................................................................................................................................................................................... What are advantages of LINQ? ................................................................................ What are Quantifiers? ................8 Q2................................................................................................................................................. 1 Dedication .............................................................................................................................................................................................................. 13 Q9................................................8 Q3...............................................9 Q5............com Handy Tricks For Beginners & Professionals 6 ........................9 Q7...... What is LINQ provider and what are different types of LINQ providers? ............. 15 Q12....................... 8 Q1.......................................................................................................................................... What are disadvantages of LINQ? .... 18 Q21.......... What are different methods to write LINQ Query? ................ What are aggregate operators? ...... 16 Q14...... 11 Q8... 18 Q20...................................................... ........................ 31 Q44...................com Handy Tricks For Beginners & Professionals 7 ......................... 22 Q29......................... 23 Q32. How can you create Expression Trees? . 31 Q45............ What is data context class? Explain its role? ............ 19 Q25..................... 21 Q26............................................................................... How Expressions Trees are different from Lambda Expression? ................... How to write LINQ query for Inner Join with OR condition?........ What is difference between LINQ and Stored Procedures? ...................................................... What are deferred execution and immediate execution? ......................................................................Load()? ........ 28 Q37......................................................................... What is difference between IEnumerable and IQueryable? ................................................................................................... 34 Q49............................... All and Contains? ............ 29 Q40..... 22 Q28........ What is difference among Any............................................................................ 28 Q36............................................ How to write LINQ query for Inner Join with and condition? .......... What is explicit loading?.............................................................................. 36 www................dotnet-tricks.................................................. What is difference between IEnumerable and IList? ................. 30 Q43........................................ 33 Q48......................... What are disadvantages of LINQ over Stored Procedures? ......... What are different types of joins in LINQ? ............... 21 Q27.......................................................................................................................................................................... What is SQL metal in LINQ? .... when LINQ to SQL is used? ......................................................................................................... Write LINQ query to find 2nd highest salary? .... How to use GroupBy in LINQ? ....... 30 Q42........................................................................................................................................... 22 Q30..................................................... 34 Q50............................................................................... What is difference between into and let keyword in LINQ? ................. What is difference between XElement......................................... What is Expression Trees? ............................................ 35 Q54... How to use Having in LINQ? ....................NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Q24................. 35 Q55.................................... What is the extension of the file..................... 35 Q53................................................Join our .Load() and XDocument............... How can you handle concurrency at field level in LINQ to SQL?............................. 30 Q41... What are lazy/deferred loading and eager loading? ......................................................... What is difference between XElement and XDocument? ..... 26 Q34......................... Can you disable lazy/deferred loading? ................ 29 Q39.......................................................................... 22 Q31.................................................................................. Explain Union............................................ How can you handle concurrency in LINQ to SQL? ......... 26 Q33........................................................................... When var or IEnumerable is used to store query result in LINQ? .. What is Expression?.......... 32 Q46...............NET and LINQ to SQL? . 34 Q51..................................................... 29 Q38.......................................... How LINQ query is compiled to Expression Trees? ............................................................................................................................. 26 Q35........ 35 Q52.......................... 33 Q47.................... What is difference between Select and SelectMany in LINQ? ..................... Intersect and Except? ................................................................................................. What is difference between ADO.................................................... XML documents.e.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 1 LINQ Q1. LINQ to SQL (DLINQ) It is specifically designed to work with only SQL Server database. It enables you to query the data from the various data sources like SQL databases.NET. This powerful feature helps you to avoid run-time errors. System.0).NET LINQ to ADO.NET framework languages like C# and VB. What is LINQ and why to use it? Ans. by using a SQL Query like syntax with . LINQ to ADO.NET Datasets.NET Classes. C# 3. 2. and others.NET is used to query data from different databases like as SQL Server.5 including Visual Studio 2008. Oracle. It offers a new way to query objects with many powerful features like filtering. Generics etc. it can be divided into three flavours:I.0 and VB. There are following three flavors of LINQ: 1. Which namespace is necessary to use LINQ? Ans.NET framework languages like C# and VB. Hence you don’t need to learn the different ways to query different data sources. LINQ stands for "Language Integrated Query" and pronounced as "LINK".NET 2008 (VB 9. Why LINQ LINQ has full type checking at compile-time and IntelliSense support in Visual Studio. LINQ also provides a uniform programming model (i. LINQ to Objects It enables you to query any in-memory object like as array. LINQ was introduced with . since it used the .NET. What are different flavors of LINQ? Ans.dotnet-tricks. It is an object-relational mapping (ORM) framework that allows 1-1 mapping of SQL Server database to .Linq namespace is necessary for writing LINQ queries and to implement it. ADO.NET Framework 3. Q2. www. collection and generics types.com Handy Tricks For Beginners & Professionals 8 . These classes are automatically created by the wizard based on database table and we can use these classes immediately. Further.Join our . ordering and grouping with minimum code. Q3. common query syntax) to query various data sources. Web services and any other objects such as Collections. common query syntax) to query data sources (like SQL databases. Its Query can be reused. Q4. It can be used to query and manipulate any database (like Oracle. manipulating. III. 2.com Handy Tricks For Beginners & Professionals 9 .NET Training Programs in Delhi/Noida Call Us : +91-9871749695 II. It is an object-relational mapping (ORM) framework that allows 1-1 mapping . 4.) that can be query with ADO.0. 3.Join our .) including SQL Server. LINQ to XML (XLINQ) This allows you to do different operations on XML data source like querying or reading. MySQL. LINQ to Datasets It is an easy and faster way to query data cached in a Dataset object. 3. It supports various powerful features like filtering.Xml.NET.e.dotnet-tricks. ADO. PLINQ helps you to write a LINQ query which will be execute simultaneously or parallel on different processors. you have to recompile it and redeploy its dll to the server. Q6. LINQ to Entities In many ways. 4. and DB2 etc. and saving changes to XML documents. Generics etc. There are following three ways to write LINQ Query: www. MySQL. It has full type checking at compile-time and IntelliSense support in Visual Studio. 1-many mapping and many-many mapping of a database to . What are different methods to write LINQ Query? Ans. Q5.NET Entity Framework.NET debugger. This powerful feature helps you to avoid run-time errors. Various Web services and any other objects such as Collections. it can be used to query any database (like Oracle. What are advantages of LINQ? Ans. filtering.Linq namespace contains classes for LINQ to XML.NET Classes. If you have done some changes in your query.) 2.NET Datasets. modifying. sorting) on Dataset using LINQ Syntax. PLINQ use the power of parallel programming which targets the Task Parallel Library. It provides a uniform programming model (i. Parallel LINQ (PLINQ) PLINQ was introduced with . LINQ doesn’t take the full advantage of SQL features like cached execution plan for stored procedure. ordering and grouping with minimum code. System. What are disadvantages of LINQ? Ans. This allows you to do further data manipulation operations (like searching. XML documents. Performance is degraded if you don't write the LINQ query correctly. LINQ is not good to write complex queries like SQL. There are following advantages of using LINQ: 1.NET Framework 4. DB2 etc. 3. it looks like LINQ to SQL. Unlike LINQ to SQL. It also allows debugging through . it is called ADO. It is a parallel implementation of LINQ to Objects. Now. There are following disadvantages of using LINQ: 1. 5. 4. Query Expression Syntax: from in let where order by select group into [identifier] [source collection] [expression] [boolean expression] [expression(ascending/descending)] [expression] [expression] by [expression] [expression] Query Expression Example: // Datasource List<int> numbers = new List<int>() { 1. 10 }. 8.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 1.NET CLR. which is usually a collection of type IEnumerable<T> or IQueryable<T>.com Handy Tricks For Beginners & Professionals 10 . 6. 3. 9. // Query based syntax IEnumerable<int> query = from num in numbers where num > 5 && num < 10 select num.Join our . 3. The result of a query expression is a query object.OrderBy [expression(ascending/descending)] . 5. 2.8. 4. 4. 7. This syntax is easy to read and write and at compile time. Method Invocation (Method Syntax) Method syntax is complex as compared to Query expression since it uses lambda expression to write LINQ query.9 2.Where [boolean expression] . Hence at compile time. which is usually a collection of type IEnumerable<T> or IQueryable<T>. 8.dotnet-tricks.7. 9.GroupBy [expression] Method Invocation Example: // Datasource List<int> numbers = new List<int>() { 1. The result of a Method syntax is also a query object. 10 }.Select [expression] . It is easily understood by . //result: 6. Query Expression (Query Syntax) Query expression syntax is like as SQL query syntax with just a few minor deviations. 2. 5. 7. Method Invocation Syntax: [source collection] . query expression is converted into Method Invocation. www. Query expression is converted into Method Invocation. 6. 7. // implicitly typed int i = 20. Mixed Syntax You can use a mixture of both syntax by enclosing a query expression inside parentheses and make a call to method. Suppose you are joining two tables and retrieving data from both the tables then the result will be an anonymous type since data will come from both the tables. // Mixed syntax int query = (from num in numbers where num > 5 && num < 10 select num). //explicitly typed var str = "1". var is an anonymous type. 7. 8. so that var type may behave like the new type assigned to it.Join our . 3. var.Count().EmpID. 5. //declaration and initialization var num = 0. www. It is used to declare implicitly typed local variable means it tells the compiler to figure out the type of the variable at compile time. execution) between Query Syntax and Method Syntax.dotnet-tricks. 9. //result: 4 Note: There are no semantic differences (in terms of performance. //result: 6. var q = (from e in context.Where(num => num > 5 && num < 10).0. hence use it whenever you don't know the type of output or it is anonymous. // Datasource List<int> numbers = new List<int>() { 1.DeptID equals d. 10 }. 2.8.DeptID select new { e. A var variable must be initialized at the time of declaration.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 // Method based syntax IEnumerable<int> query = numbers.Employee join d in context. //explicitly typed var s2 = s.com Handy Tricks For Beginners & Professionals 11 . Q7.Department on e. DataContext context = new DataContext().9 3. For Example: var i = 20.var data type was introduced with C# 3. string s = "string". // implicitly typed Basically. 6. Expression assigned to var must be executed at compile time to know the type of output. How var type is different from anonymous type? Ans. 4. int salary.DeptName. } } } The anonymous type is very useful when you want to shape the result in your desired form like this: DataContext context = new DataContext(). Anonymous Type. public string Name { get { return name.Issue }.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 e. Address = "Noida". IssueNumber = "#" + book. private string address. } } public int Salary { get { return salary.dotnet-tricks. } set { address = value. www. In above example.Price > 200 orderby book. d.An anonymous type is a simple class generated by the compiler within IL to store a set of values. I change the name of the “Issue” field of Book table to “IssueNumber” and add # before value to get desired output. At compile time.Name.IssueDate descending select new { Name = book. var result = from book in context. Salary = 21000 }.com Handy Tricks For Beginners & Professionals 12 .DeptLocation }). } set { name=value } } public string Address { get { return address.Books where book. as follows: class __Anonymous1 { private string name.FirstName. d. } set { salary = value. var data type and new keyword is used to create an anonymous type. var emp = new { Name = "Deepak".Join our . the compiler will create an anonymous type. declared without parenthesis can be assigned to a delegate with any signature. Typically. Lambda expression Syntax (Input-parameters) => expression-or-statement-block Types of Lambda expression www. An anonymous method behaves like a regular method and allows you to write inline code in place of regular method.Join our . An anonymous method. Call Us : +91-9871749695 What is anonymous method? Ans. 4.0. Q9. static void Main(string[] args) { //anonymous method using delegate keyword del d1 = delegate(int x. optional parameters and return type. We use anonymous method in event handling. A variable. declared inside the anonymous method can’t be accessed outside the anonymous method.0. The left side of the lambda operator "=>" represents the arguments of anonymous method and the right side represents the method body. class Program { //delegate for representing anonymous method delegate int del(int x. 6. The concept of lambda expression was introduced in C# 3.WriteLine(z1). It is just a new way to write anonymous method. What is lambda expression? Ans. Console. } } //output: 6 Key points about anonymous method 1. lambda expression is a more concise syntax of anonymous method. int y).NET Training Programs in Delhi/Noida Q8. int z1 = d1(2. A variable. 3). 2. int y) { return x * y. The concept of anonymous method was introduced in C# 2. 5. 3. }. It is created using the delegate keyword and doesn’t have its name and return type. At compile time all the lambda expressions are converted into anonymous methods according to lambda expression conversion rules. it has only body. An anonymous method is an inline unnamed method in the code. Unsafe code can’t be accessed within an anonymous method.dotnet-tricks. declared outside the anonymous method can be accessed inside the anonymous method. An anonymous method can’t access the ref or out parameters of an outer scope. In this way.com Handy Tricks For Beginners & Professionals 13 . an anonymous method has no name. int y) => { return x * y. }. // or (int x. 3). //anonymous method using statement lambda del d2 = (x. int y) { return x * y. y) => x * y. What is Extension method? Ans. // here x*x is expression Anonymous Method and Lambda Expression example: class Program { //delegate for representing anonymous method delegate int del(int x.dotnet-tricks.WriteLine(z1). Statement Lambda -Statement lambda has a statement block on the right side of the lambda operator "=>". int z3 = d3(4.WriteLine(z3). Console. 2. } } //output: 6 9 12 Q10. static void Main(string[] args) { //anonymous method using expression lambda del d1 = (x. Extension methods are used to add new behaviors to an existing type without altering. An extension method is a static method of a static class that can be invoked like as an instance method syntax. }. 3). // or (int x. x => { return x * x.Expression lambda has only an expression (no return statement or curly braces). int z1 = d1(2.Join our . int y) => x * y. Other parameters of extensions types can be of any types (data type). 3). x => x * x. y) => { return x * y. }. on the right side of the lambda operator "=>". Console. www.com Handy Tricks For Beginners & Professionals 14 . }. In extension method "this" keyword is used with the first parameter and the first parameter will be of type that is extended by extension method. //anonymous method using delegate keyword del d3 = delegate(int x. int z2 = d2(3. Expression Lambda . int y). Console.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 1.WriteLine(z2). An extension method first parameter specifies the type of the extended object. '.'.' }). VB.Length. //calling extension method int i = s. The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. LINQPad is a most popular tool for testing LINQ queries. An extension method couldn't override the existing instance methods. } } class Program { public static void Main() { string s = "Dot Net Tricks Extension Method Example". } } //output: //6 Key points about extension method 1. Console.com Handy Tricks For Beginners & Professionals 15 . It is a standalone application developed by Joseph Albahari that allows you to execute LINQ queries or other C#. 4. T-SQL statements. An extension method cannot be used with fields.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Example: //defining extension method public static class MyExtensions { public static int WordCount(this String str) { return str. 6. properties or events.dotnet-tricks. Q11. An extension method is defined as static method but it is called like as an instance method. 5.WordCount(). An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method. Compiler will cause an error if you will try to call one of them extension method.WriteLine(i). and it is preceded by the "this" keyword.Join our . 2. F#.Split(new char[] { ' '. www. What is LINQPad? Ans. '. 3. It can also be used with others third-party drivers to support most of the . Q13. LongCount. 1. Some of them are as: All() Any() Contains() SequenceEqual() What are different types of operators in LINQ? LINQ provides you various operators to write a LINQ query. What is LINQ Insight? Ans. Ans. 2. Average. It provides viewing of SQL. Various types of operators are given below: Operator Type Aggregate Concatenation Conversions www.linqpad.com Operator Name Aggregate. generated for LINQ to Entities. LINQ to SQL. It is an alternative of LINQPad which is developed by Devart. OfType. LINQPad supports Entity Framework. or Visual Studio 2013. Count. Sum Concat Cast. and LinqConnect.Join our . Q14.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 It can be downloaded at from www. NHibernate. Q12. and profiling data access events for Entity Framework.dotnet-tricks. It can be used without visual studio. Q15. ToLookup. and LINQ to SQL. WCF Data Services. ToList.NET ORMs. ToDictionary. 3. LINQ to NHibernate. Visual Studio 2012. Min. AsEnumerable Handy Tricks For Beginners & Professionals 16 . LinqConnect. Ans.net. What are Quantifiers? LINQ extension methods which return a boolean value are called as Quantifiers. LINQ to SQL. 4. Max. ToArray. and Microsoft DataMarket Service out-of-the-box. To test your LINQ queries it requires Visual Studio 2010. What LINQ providers are supported by LINQPad? Ans. //result:150 //Average of numbers Console. ElementAt.dotnet-tricks. 30.Max()). //Sum of numbers Console. //Cast to Array int[] strArray = data. 30.Average()). Q17. //Try to get element at specified position www. 20. } Q18. i++) { Console. List<int> data = new List<int> { 10. SingleOrDefault. 20.WriteLine(data. OrderByDescending.Sum()). 50 }. //result:10 20 30 40 50 for (int i = 0. Aggregate operators perform calculations on a set of values and return a single value. 40.NET Training Programs in Delhi/Noida Element Equality Generation Grouping Join Ordering Partitioning Projection Quantifier Restriction Set Q16. LastOrDefault. Except. i < strArray. 30. Select. TakeWhile. FirstOrDefault.WriteLine(data. Intersect.com Handy Tricks For Beginners & Professionals 17 . Max. Distinct What are aggregate operators? Ans. ToList. Call Us : +91-9871749695 Single.Length. Empty GroupBy Join. List<int> data = new List<int> { 10. Conversion operators convert the type of input objects into a specific type or sequence. The aggregate operators are Average.Cast<int>(). and Sum. 50 }. FirstOrDefault.Write(strArray[i] + " "). //result:30 //Max of numbers Console. Range. GroupJoin OrderBy. Count. 50 }. LastOrDefault. Element operators return a single element or a specific element from a collection.Join our . 40. ThenBy. ElementAtOrDefault SequenceEqual Repeat. 40. The elements operators are Single. ToArray and ToDictionary. First. ThenByDescending. SingleOrDefault.WriteLine(data. 20. Min. Last. Take. The aggregate operators are AsEnumerable. What are element operators? Ans.ToArray(). SkipWhile. Last. //result:50 What are conversion operators? Ans. All. Reverse Skip. List<int> data = new List<int> { 10. Any Where Union. First. Cast. SelectMany Contains. Last()). if no match is found for that element in the collection.WriteLine(data.WriteLine(data.First(d => d <= 20)). SingleOrDefault.dotnet-tricks. since default value is 0 //Try to get single element // data.SingleOrDefault(d => d == 100)). //Exception:Sequence contains more than one element //Try to get single element if exist otherwise returns default value // data. An exception is thrown.SingleOrDefault(). since default value is 0 Q19.WriteLine(data.WriteLine(data.Single(). Ans. A default value is returned.It returns a single specific element from a collection of elements if element match found. An exception is thrown.ElementAt(1)). //result:10 //try to get first element from matching elements collection else returns default value Console.WriteLine(data. since default value is 0 Console.ElementAtOrDefault(10)). //result:10 Console. SingleOrDefault . A default value is returned. What is difference among Single. //Exception:Sequence contains more than one element //try to get single element 10 if exist Console. FirstOrDefault .com Handy Tricks For Beginners & Professionals 18 . First and FirstOrDefault.SingleOrDefault(d => d >= 100)). Q20. //result:10 //try to get single element 100 if exist otherwise returns default value Console. //result:0.First()).WriteLine(data. if no match is found for that element in the collection.Join our .WriteLine(data.NET Training Programs in Delhi/Noida Console. //result:0.It returns first specific element from a collection of elements if one or more than one match found for that element. Single .It returns first specific element from a collection of elements if one or more than one match found for that element.It returns a single specific element from a collection of elements if element match found.Single(d => d == 10)). else returns default value Console. //result:0. if more than one match found for that element in the collection. //result:50 //try to get first element from matching elements collection Console. When to use Single. Call Us : +91-9871749695 //result:20 //Try to get element at specified position if exist. 1. An exception is thrown. When you want an exception to be thrown if the result set contains many records. www. First .WriteLine(data. if none or more than one match found for that element in the collection. First and FirstOrDefault? Ans. use Single or SingleOrDefault. SingleOrDefault. if no match is found for that element in the collection. First and FirstOrDefault? You should take care of following points while choosing Single. SingleOrDefault. When you want a default value is returned if the result set contains no record. Q24. use First or FirstOrDefault. list of list to list. LINQ to SQL. "Windows Azure".Add(emp1). use FirstOrDefault.e. The different types of LINQ providers are LINQ to Objects. FirstOrDefault usually perform faster as compared SingleOrDefault. Skills = new List<string> { "C". Employee emp3 = new Employee { Name = "Lalit". nested collection. LINQ is the best way to do further data manipulation operations (like searching. Select operator produce one result value for every source value while SelectMany produce a single result that contains a concatenated value for every source value. Skills = new List<string> { "SQL Server".NET Training Programs in Delhi/Noida Call Us : +91-9871749695 2.dotnet-tricks.e. Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i. } public List<string> Skills { get. A LINQ provider is a library which helps you to execute a given query against a data source. Actually. "Java" } }. Q22. Q21. What is LINQ provider and what are different types of LINQ providers? Ans. class Employee { public string Name { get. Select and SelectMany are projection operators. filtering. SQL query is able to populate the dataset from the database but not able to retrieve a particular value from the dataset. set. "C#". use SingleOrDefault. When you want a default value if the result set contains no record. Employee emp2 = new Employee { Name = "Karan".Add(emp2). Q23. employees. "SQL Server" } }. When you always want one record no matter what the result set contains. Which one is fast between SingleOrDefault and FirstOrDefault? Ans. set. www.NET" } }.NET MVC". since these iterate the collection until they find the first match. "C++". While SingleOrDefault iterate the whole collection to find one single match. 3. employees.Join our . SelectMany operator flatten IEnumerable<IEnumerable<T>> to IEnumrable<T> i. Employee emp1 = new Employee { Name = "Deepak". 4. employees.com Handy Tricks For Beginners & Professionals 19 .Add(emp3). sorting) on Dataset in an efficient way. LINQ to DataSet is useful to run strongly typed queries on multiple datasets. "ASP. Skills = new List<string> { "C#". LINQ to XML LINQ to Datasets and LINQ to Entities. What are advantages of using LINQ on DataSet? Ans. "ASP. } } class Program { static void Main(string[] args) { List<Employee> employees = new List<Employee>(). What is difference between Select and SelectMany in LINQ? Ans. // Two foreach loops are required to iterate through the results // because the query returns a collection of arrays.WriteLine(skill).dotnet-tricks.SelectMany(emp => emp.WriteLine(skill).Join our .Skills).Select(e=> e.ReadKey(). } Console. Console. // Only one foreach loop is required to iterate through the results // since query returns a one-dimensional collection. } Console. Console.WriteLine("Using Select():\n").NET C# ASP. } } /*Output : Using Select(): C C++ Java SQL Server C# ASP.com Handy Tricks For Beginners & Professionals 20 . foreach (string skill in resultSelectMany) { Console.WriteLine().NET Training Programs in Delhi/Noida Call Us : +91-9871749695 // Query using Select() IEnumerable<List<String>> resultSelect = employees.Skills). } // Query using SelectMany() IEnumerable<string> resultSelectMany = employees. foreach (List<String> skillList in resultSelect) { foreach (string skill in skillList) { Console.WriteLine("Using SelectMany():").NET MVC Windows Azure SQL Server www. What is difference between into and let keyword in LINQ? Ans. "Rajesh".Salary. string[] names = { "Rohan". "C#".Count()) where groupingEmp.com Handy Tricks For Beginners & Professionals 21 .NET". Q26. bool IsFirstLetterR = names.NET MVC Windows Azure SQL Server */ Q25.All(name => name. "LINQ" }.StartsWith("R")). It hides the previous range variable and create a temporary range variable which you can be used further.This is used to store the results of a group.Key.Contains("Swimming"). Into . "Rita" }. All and Contains? Ans. It returns true if at least one element satisfy the condition else returns false if they do not. join or select clause into a temporary variable. DataContext context = new DataContext(). groupingEmp. It returns true if match found else returns false if no match found. "ASP. "Cricket".NET C# ASP. //return true string[] skills = { "C".StartsWith("C")).Salary == avgsalary select new { groupingEmp.Sum(gEmp => gEmp. "Watching Moview"}. bool IsHobby = hobbies.dotnet-tricks. emp. It returns true if all the elements satisfy the condition else returns false if they do not.Key.It checks whether all the elements in a collection satisfy a specified condition.Salary. bool IsFirstLetterC = skills. "Raj".tblEmployee group emp by new { emp.Salary) / groupingEmp. "C++". What is difference among Any. "Rahul".Key. www. //return true Contains . "Singing".Join our .NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Using SelectMany(): C C++ Java SQL Server C# ASP.It checks for an element match in a collection.Any(s => s.It checks whether at least one element in a collection satisfy a specified condition. All .EmpId } into groupingEmp let avgsalary = (groupingEmp.EmpId }. var q=from emp in context. //return true string[] hobbies = { "Swimming". Any . 7. a query is not executed at the point of its declaration. int[] numbers2 = { 5.2.4 Q28.dbml. Intersect and Except? Union .It returns the difference between two collections. IEnumerable<int> except = numbers1. int[] numbers1 = { 1. 10 }. Deferred Execution: In case of differed execution. 6. 7. //5 Except . 2. update and delete operations over the data in the database. 5}. Ans. 2.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Let .3.6.It returns the intersection of two collections. IEnumerable<int> intersection = numbers1. Explain Union. 5}. 10 }. What is the extension of the file. 2. 9. Contains the connection string information. It is executed when the Query variable is iterated by using loop like as for. It is just opposite to intersect. Q29.com Handy Tricks For Beginners & Professionals 22 .dotnet-tricks. methods to connect to the database and manipulating the data in the database.Except(numbers2). 9. 3. DataContext context = new DataContext(). 3. 8.5. 7.It returns the union of two collections. foreach. 8. In union elements will be unique.7. What are deferred execution and immediate execution? Or What is difference between deferred execution and immediate execution? Ans. What is data context class? Explain its role? Ans. Contains several methods that send updated data from LINQ to SQL entity classes to the database. With data context. //1. int[] numbers1 = { 1. 3. var query = from customer in context. 10 }. 6. Q30. 4. 2. int[] numbers2 = { 5. insert. 9. int[] numbers2 = { 5.8. 4. It doesn’t hide the previous range variable and create a new variable which can be used further with previous variable.Customers www. 8. we can perform select. 5}. It has following responsibilities: 1. Intersect(numbers2).10 Intersect .Union(numbers2). 3.4. Ans. Methods can also be mapped to stored procedures and functions.2. 6. //1. 4. 4. Data context class is a LINQ to SQL class that acts as a medium between a SQL server database and LINQ to SQL entities classes mapped to that database. Q27.3.This is used to store the result of a sub expression into a new variable.Join our . when LINQ to SQL is used? The extension of the file is . int[] numbers1 = { 1. IEnumerable<int> union = numbers1.9. com Handy Tricks For Beginners & Professionals 23 . } } Generated SQL Query by LINQ Pad will be: www.WriteLine(Emp. caused Immediate Execution.Department. // Query execute here Immediate execution doesn’t provide the facility of query reusability since it always contains the same data which is fetched at the time of query declaration. What are lazy/deferred loading and eager loading? Or What is difference between lazy/deferred loading and eager loading? Ans. Sum. Lazy/Deferred Loading: In case of lazy loading.Take(3).dotnet-tricks.Name). List etc. You can force a query to execute immediately of by calling ToList.EmpID).WriteLine(Dept.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 where customer. DataContext context = new DataContext(). // Lazy loading foreach (var Dept in query) { Console. By default LINQ supports lazy loading.Join our . } A LINQ query expression often causes deferred execution. a query is executed at the point of its declaration.Count(). related objects (child objects) are not loaded automatically with its parent object until they are requested. var query = context. // Query does not execute here foreach (var Customer in query) // Query executes here { Console.Name). Count. ToArray methods. foreach (var Emp in Dept. Q31. For Example: DataContext context = new DataContext().City == "Delhi" select customer. Deferred execution provides the facility of query reusability.Customers where customer. The query which returns a singleton value (a single value or a set of values) like Average.City == "Delhi" select customer).WriteLine(Customer. Immediate Execution: In case of immediate execution. var query = (from customer in context.Employee) { Console. since it always fetches the updated data from the data source which exists at the time of each execution. [CreatedDate] AS [CreatedDate]. [Extent1].[Name] AS [Name]. [Extent1].[Employee] AS [Extent1] WHERE [Extent1]. [Extent1]. Eager loading: In case of eager loading. FROM [dbo].EndRegion SELECT [Extent1].EndRegion SELECT [Extent1]. one for the Categories and three times for the Products associated to the Categories. you have 4 SQL queries which means calling the database 4 times. FROM [dbo].Region Parameters DECLARE @EntityKeyValue1 Int = 3 -. [Extent1]. [Extent1].[Name] AS [Name]. child entity is populated when it is requested.[DeptID] AS [DeptID].dotnet-tricks. [Extent1].[DeptID] = @EntityKeyValue1 GO -.[DeptID] AS [DeptID].[DeptID] = @EntityKeyValue1 GO -. FROM [dbo].[Employee] AS [Extent1] WHERE [Extent1]. [Extent1].com Handy Tricks For Beginners & Professionals 24 .NET Training Programs in Delhi/Noida Call Us : +91-9871749695 SELECT TOP (3) [c].[Name] AS [Name].[Department] AS [d] GO -. To use Eager loading you need to use Include() method.[EmpID] AS [EmpID].[Name] AS [Name].Region Parameters DECLARE @EntityKeyValue1 Int = 1 -. [Extent1].Region Parameters DECLARE @EntityKeyValue1 Int = 2 -.[Employee] AS [Extent1] WHERE [Extent1].[CreatedDate] AS [CreatedDate]. [Extent1]. In this way.EndRegion SELECT [Extent1]. [Extent1].Join our . [Extent1].[DeptID] AS [DeptID].[Salary] AS [Salary]. [Extent1].[DeptID] = @EntityKeyValue1 In above example.[DeptID] AS [DeptID].[Salary] AS [Salary].[CreatedDate] AS [CreatedDate].[CreatedDate] AS [CreatedDate] FROM [dbo]. related objects (child objects) are loaded automatically with its parent object. [c]. www.[EmpID] AS [EmpID].[Salary] AS [Salary]. [c].[EmpID] AS [EmpID]. [CreatedDate] AS [CreatedDate].[CreatedDate] AS [CreatedDate] FROM [dbo].com Handy Tricks For Beginners & Professionals 25 .[Name] [c].[EmpID] IS NULL) THEN CAST(NULL AS int) ELSE 1 END AS [D1] FROM (SELECT TOP (3) [d].[Name] AS [Name]. var query = context.Take(3). for the Categories and the Products associated to the Categories.[DeptID] AS [DeptID1].[Salary] AS [Salary]. [Project1]. you have only one SQL queries which means calling the database only one time.[DeptID] = [Extent2]. child entity is populated with parent entity. [Project1]. // Eager loading foreach (var Dept in query) { Console. [Extent2].[Name] AS [Name].[Employee] AS [Extent2] ON [Limit1]. www. [Limit1]. [Extent2]. [Extent2].[D1] ASC AS [Name].Department.[Department] AS [d] ) AS [Limit1] LEFT OUTER JOIN [dbo]. } } Generated SQL Query will be: SELECT [Project1]. foreach (var Emp in Dept.WriteLine(Emp. [Extent2]. [Project1].[EmpID] AS [EmpID].[CreatedDate] AS [CreatedDate].[EmpID] AS [EmpID].Join our .[DeptID] AS [DeptID]. [Project1].[CreatedDate] AS [CreatedDate1] CASE WHEN ([Extent2]. [d].Name).[DeptID] AS [DeptID].[Name] AS [Name1].Include("Employee").EmpID).[DeptID] AS [DeptID1].[EmpID]) AS [Project1] ORDER BY [Project1].NET Training Programs in Delhi/Noida Call Us : +91-9871749695 For Example: DataContext context = new DataContext(). [Extent2]. [Project1].[D1] AS [D1].[DeptID] AS [DeptID]. In this way. [Project1].[Salary] AS [Salary]. [Project1]. [Limit1].[Name] AS [Name1].WriteLine(Dept.[DeptID] ASC.[CreatedDate] AS [CreatedDate1] FROM (SELECT [Limit1].dotnet-tricks.Employee) { Console. [Project1]. [Project1]. In above example. com Handy Tricks For Beginners & Professionals 26 . www. 1.ProductID equals od.Entry(cat). you can turn off the lazy loading feature by setting LazyLoadingEnabled property of the ContextOptions on context to false.dotnet-tricks. To do so you have to use the load method on the related entity’s navigation property. related objects (child objects) are not loaded automatically with its parent object until they are requested. Q34. LINQ has a JOIN query operator that provides SQL JOIN like behavior and syntax. DataContext context = new DataContext(). pd. INNER JOIN . For example: // Load the products related to a given category context. Q33.OrderID.Reference(p => p. context.ToList(). Now you can fetch the related objects with the parent object in one query itself. A group join produces a sequence of object arrays based on properties equivalence of left collection and right collection. 2.ProductID orderby od. pd. If lazy loading is disabled then it is still possible to lazily load related entities by explicit loading.ContextOptions.Orders on pd.ProductID. od.Inner join returns only those records or rows that match or exists in both the tables.NET Training Programs in Delhi/Noida Q32.UnitPrice. Ans. What are different types of joins in LINQ? Ans.Price. GROUP JOIN. pd.LazyLoadingEnabled = false. What is explicit loading? Ans. od.Load(). There are four types of Joins in LINQ. }). then it is called a group join.Quantity. var q = (from pd in context.Join our . Call Us : +91-9871749695 Can you disable lazy/deferred loading? Yes.Products join od in context.Product). If right collection has no matching elements with left collection then an empty array will be produced.When a join clause use an INTO expression.OrderID select new { od. By default.Name. pd.Price.com Handy Tricks For Beginners & Professionals 27 . pd.Name.tblProducts join od in context.ProductID.ProductID select new { OrderID = rt.Quantity.ProductID select new { pd. }). 3. Order = t }). pd. rt.ToList(). In LINQ to achieve CROSS JOIN behavior.Cross join is a Cartesian join means Cartesian product of both the tables.UnitPrice.CustomerID.Orders select new { c.UnitPrice. This join does not need any condition to join two tables.tblOrders on pd.Name. If there are no columns matching in the right table. var q = from c in context. var q = (from pd in context.ProductID into t from rt in t. DataContext context = new DataContext().DefaultIfEmpty() orderby pd. 4. it returns NULL values.ProductID into t orderby pd.dotnet-tricks. there is no need to use Join clause and where clause.LEFT JOIN returns all records or rows from left table and from right table returns only matched records.ProductID. pd. This join returns records or rows that are multiplication of record number from both the tables’ means each row on left table will relate to each row of right table. LEFT OUTER JOIN . pd. We will write the query as shown below. Basically. In LINQ to achieve LEFT JOIN behavior.OrderID.Join our .tblOrders on pd.ProductID equals od.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 DataContext context = new DataContext(). it is mandatory to use "INTO" keyword and "DefaultIfEmpty()" method.ProductID equals od. CROSS JOIN. www.Customers from o in context. rt. var q = (from pd in context. GROUP JOIN is like as INNER-EQUIJOIN except that the result sequence is organized into groups.ToList().tblProducts join od in context. We can apply LEFT JOIN in LINQ like as: DataContext context = new DataContext(). ord. you need to apply inner join with or condition. How to write LINQ query for Inner Join with OR condition? Ans.ContactNo} equals new {a=ord.[CustID]) = [t1]. Both the comparing fields should define either NULL or NOT NULL values.[OrderID]. [t1]. If one of them is defined NULL and other is defined NOT NULL then we need to do typecasting of NOT NULL field to NULL data type like as above fig. Sometimes.Join our . var q=from cust in context.com Handy Tricks For Beginners & Professionals 28 .dotnet-tricks. Q35.Address. Sometimes.[Address].ContactNo} select new { cust.[CustomerID]) AND ([t0]. o.[ContactNo]) Note 1. both the anonymous types should have exact same number of properties with same name and Datatype otherwise you will get the compile time error "Type inference failed in the call to Join". [t1].tblCustomer from ord in context. To write query for inner join with and condition you need to make two anonymous types (one for left table and one for right table) by using new keyword and compare both the anonymous types as shown below: DataContext context = new DataContext().[Quantity] FROM [tblCustomer] AS [t0] INNER JOIN [tblOrder] AS [t1] ON (([t0].tblCustomer join ord in context. How to write LINQ query for Inner Join with and condition? Ans.Quantity }. var q=from cust in context. ord. To write query for inner join with or condition you need to use || operator in where condition as shown below: DataContext context = new DataContext(). Q36.OrderDate }.CustID.tblOrder // Both anonymous types should have exact same number of properties having same name and datatype on new {a=(int?)cust. Always remember.OrderID.Name. // Generated SQL SELECT [t0]. cust. you need to apply inner join with and condition.[ContactNo] = [t1].OrderID. ord. 2.ContactName.tblOrder www. [t0].NET Training Programs in Delhi/Noida Call Us : +91-9871749695 c. 3.[Name].CustomerID. o. cust. Each group has a key.GroupBy(ord => ord. third . var query=from ord in context. Q38.Join our .Distinct()..OrderByDescending(f => f. DataContext context = new DataContext().Name.OrderID. Values>. It is used for grouping of elements based on a specified value.dotnet-tricks.Skip(1) //second.[Address]. // Generated SQL SELECT [t0].ContactNo) select new { cust. [t0].com Handy Tricks For Beginners & Professionals 29 .CustomerID || cust.Address.Select(ord=>ord.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 where (cust. There is no having operator in LINQ.[Name].Key) . [tblOrder] AS [t1] WHERE (([t0]. Q39.CustomerID into grouping select new { grouping.n-1 .[CustID]) = [t1].First() .2. Ans..Salary) . How to use GroupBy in LINQ? Ans. [t1]. It returns a collection of IGrouping<Key.nth highest salary where n=1.CustID==ord. How to use Having in LINQ? Ans..[ContactNo]) Q37.Quantity }.[OrderID]. Write LINQ query to find 2nd highest salary? OR Write LINQ query to find nth highest salary? You can find nth highest salary by writing the following query. ord. ord.ContactNo==ord.Key. www.[Quantity] FROM [tblCustomer] AS [t0].[ContactNo] = [t1]. grouping }.Salary) .[CustomerID]) OR ([t0]. but you can get the same result by using a Where clause after a Group By clause.tblEmployee. var q= context. [t1]. DataContext context = new DataContext().tblOrder group ord by ord. cust. but this is what actually happens when you supply a lambda expression to an expression tree. Expression is an abstract class which contains static methods and inherited by various types (like ParameterExpression. where they were mainly used by LINQ providers. int>> expression = (num1. where T is a delegate type. int> compiledExpression = expression. In .Expressions namespace. Q41. Using Expression Lambda .Linq. the C# compiler generates the expression tree from the provided lambda expression.) to create expression tree nodes of specific types. Q42. // Execute the expression. This transformation enables dynamic modification of executable code as well as the execution of LINQ queries in various databases and the creation of dynamic queries.Compile(). grouping }.Count()>=2 select new { grouping.0 (Visual Studio 2008). num2) => num1 + num2.dotnet-tricks. What is Expression? Ans. var q=from ord in context. Also all these expression-specific expression tree types are defined in System. This looks much more complicated. int. Expression trees represent code in a tree-like format.CustomerID into grouping where grouping. Expression Trees was first introduced in C# 3. where each node is an expression (for example. // Compile the expression Func<int. The structure of above expression trees will be like as: www. and assign a lambda expression to this instance. Q40. BinaryExpression etc. MethodCallExpression. a method call or a binary operation such as x < y). What is Expression Trees? Ans.Key. // Create an expression using expression lambda Expression<Func<int.tblOrder group ord by ord. int. You can also convert expression trees into compiled code and run it.Join our .com Handy Tricks For Beginners & Professionals 30 .NET. Ans. int result = compiledExpression(3. How can you create Expression Trees? You can create expression trees by using following two ways: 1.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 DataContext context = new DataContext().The easiest way to generate an expression tree is to create an instance of the Expression<T> type. 4). //return 7 In this example. //Create the expression Expression<Func<int. 4). Q44. //return 7 Q43. "num1"). parameters). you can create expression trees that are more complex than those that can be created from lambda expressions. int> compiledExpression = expression. In . But this is not true since you can also create and modify expression trees by using API methods i. By using the API. num2 }. every lambda expression cannot be implicitly converted into an expression tree.Expression class is used to create expression trees by using the API. a query expression is compiled to expression trees or to delegates. A common misunderstanding is that expression trees are identical to lambda expressions. int. The IEnumerable<T> type LINQ queries are compiled to delegates and IQueryable or IQueryable<T> type LINQ queries are compiled to expression trees. //Create the expression body BinaryExpression body = Expression. // Execute the expression int result = compiledExpression(3. conditional blocks.e.Parameter(typeof(int). ParameterExpression num2 = Expression. In LINQ.dotnet-tricks. and try-catch blocks.Compile().Add(num1. "num2").Parameter(typeof(int). Using Expression Tree API . int>> expression = Expression. //Create the expression parameters ParameterExpression[] parameters = new ParameterExpression[] { num1. Also. multi-line lambda cannot be implicitly converted into expression tree.e. depending on the type that is applied to query result. // Compile the expression Func<int. int>>(body. www. How Expressions Trees are different from Lambda Expression? Ans. above code can be rewritten as: //Create the expression parameters ParameterExpression num1 = Expression. the expression trees API also supports assignments and control flow expressions such as loops. Using API. without using lambda expression syntax at all.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 2.NET Framework 4. int.Join our .Lambda<Func<int.com Handy Tricks For Beginners & Professionals 31 . How LINQ query is compiled to Expression Trees? Ans. int. num2). Only expression lambda is implicitly converted an expression tree and statement lambda i. www. Here query variable. [t0].Collections Namespace Exists in System.com Handy Tricks For Beginners & Professionals 32 . What is difference between IEnumerable and IQueryable? There are following differences between ADO.NET and Entity Framework: IEnumerable IQueryable Exists in System. SELECT [t0]. Ans.CompanyName }.) and based on LINQ provider query is translated into an appropriate query (like T-SQL query). Then query provider traverse the expression tree and translate it into a query language (like T-SQL) which is appropriate for that data source.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 In short. It is first translated into the following SQL statement and then executed on SQL Server side. } IQueryProvider Provider { get.Customers where c. The C# and Visual Basic compilers compile these queries into code that builds an expression trees at runtime.Join our . Array etc.[Customers] AS [t0] WHERE [t0]. database. } } As you can see. } Expression Expression { get.Linq Namespace Best to query data from in-memory collections like Best to query data from out-memory (like remote List. LINQ to Entity etc. service) collections.City. The Type property represents the type of the element(s) that are returned when the expression tree is executed. LINQ to Entity) are result into IQueryable<T> type. c. The IQueryProvider type property hold the LINQ provider (like LINQ to SQL.City == "Delhi" select new { c. In this way. LINQ queries that execute in process are compiled into delegates while the queries that execute out of process are compiled into expression trees.dotnet-tricks.[CompanyName] FROM [dbo]. returned by this LINQ query is of type IQueryable and the declaration of IQueryable is as: public interface IQueryable : IEnumerable { Type ElementType { get.[City] = @p0 Q45. In LINQ.[City]. the above code is never actually executed inside your program. Consider the following LINQ to SQL query expression: var query = from c in db. domain-specific queries (like LINQ to SQL. IQueryable contains a property of type Expression which holds the expression tree and represents data structure equivalent to the executable code found in a query expression. Employees. You can use var or IEnumerable<T> to store the result of a LINQ query. Handy Tricks For Beginners & Professionals 33 . www.[EmpID]. Ans.[EmpName]. scenarios. query result.Join our .Where(p => p. in a list. DataContext context = new DataContext(). You should take care of following points while choosing between var and IEnumrable. [t0].NET and Entity Framework: IEnumerable IList Move forward only over a collection.Where(p => p. IEnumerable While querying data from database.execute select query on server side with all filters.Take<Employee>(10). var is also good for remote collection since var is an IEnumerable is good for in-memory collection. [t0].[Salary] FROM [Employee] AS [t0] WHERE [t0].dotnet-tricks.[Salary] FROM [Employee] AS [t0] WHERE [t0]. What is difference between IEnumerable and IList? There are following differences between ADO.Name.[EmpName] LIKE @p0 Suitable for LINQ to SQL queries. Supports custom query using CreateQuery() and Execute() methods.[EmpName] LIKE @p0 Suitable for LINQ to Object and LINQ to XML queries. Doesn’t supports custom query.StartsWith("S")). memory on client side and then filter data. Generated SQL having no Top Keyword: SELECT [t0].NET Training Programs in Delhi/Noida Call Us : +91-9871749695 While querying data from database. Hence not suitable for Support lazy loading. IQueryable type that executes query in SQL server with all filters.[EmpID]. Q46. Generated SQL having Top Keyword: SELECT TOP 10 [t0]. [t0].Employees. Doesn’t support lazy loading.Take<Employee>(10).com Useful when you want to Add or remove items from the list. load data in. IQueryable<Employee> list = context. IQueryable execute select query on server side. it can’t move Used to access an element in a specific position/index backward and between the items.[EmpName].Name. For Example: For Example: DataContext context = new DataContext(). IEnumerable<Employee> list = context. When var or IEnumerable is used to store query result in LINQ? Ans. Q47. list = list. var IEnumerable Use var type when you want to make a "custom" type Use IEnumerable when you already know the type of on the fly.[t0]. list = list. Doesn’t support add or remove items from the list.StartsWith("S")). Hence it is suitable for paging like paging like scenarios. SQL metal is a command line tool to generate code and mapping for LINQ to SQL.sdf file. Input file might be SQL Server . What is SQL metal in LINQ? Ans. Since in case of stored procedures. Hence. Q49. Ans. the database used the cached execution plan to execute that stored procedure.NET Training Programs in Delhi/Noida Call Us : +91-9871749695 Find out the no of elements in the collection after Find out the no of elements in the collection without iterating the collection. LINQ has full type checking at compile-time and IntelliSense support in Visual Studio as compared to stored procedure. 4. 1. Doesn’t support further filtering. Supports further filtering. you need to provide a SQL script for deployment but in case of LINQ everything gets complied into the DLLs. Q50. It perform the following actions: 1. 2.mdf file.dbml) file for customization from a database. LINQ also supports various . and Output options. Generate code and mapping attributes or a mapping file from a .com Handy Tricks For Beginners & Professionals 34 . type sqlmetal /? at command prompt. 7. LINQ query takes more time in execution as compared to stored procedures. 1. Deploying LINQ based application is much easy and simple as compared to stored procedures based. LINQ provides the uniform programming model (means common query syntax) to query the multiple databases while you need to re-write the stored procedure for different databases.dotnet-tricks. Extraction options. It automatically generates the entity classes for the given database. Stored procedures are faster as compared to LINQ query since they have a predictable execution plan and can take the full advantage of SQL features.dbml intermediate file. . Generate an intermediate database markup language (. Generate source code and mapping attributes or a mapping file from a database. Q48. This powerful feature helps you to avoid run-time errors. Syntax for SQL metal at command prompt sqlmetal [options] [<input file>] To view the options list. It is included in Windows SDK that is installed with Visual Studio. when a stored procedure is being executed next time. Ans. 6. You can define various options such as Connection Options. Hence. 5.Join our . LINQ query is compiled each and every time while stored procedures re-used the cached execution plan to execute.NET debugger as compared to stored procedure. or a . Hence you need to deploy only DLLs. 3. 3. iterating the collection. 2.dbml file. LINQ allows debugging through . Stored procedure is a best way for writing complex queries as compared to LINQ. What is difference between LINQ and Stored Procedures? There are the following differences between LINQ and Stored Procedures. What are disadvantages of LINQ over Stored Procedures? There are the following disadvantages of LINQ over Stored Procedures.NET framework features like multi –threading as compared to stored procedures. www. What is difference between XElement and XDocument? Ans. It has full type checking at run-time and no IntelliSense support in Visual Studio. 1. 5.Load () when you want to load any markup before the top-level element.Load() and XDocument. Use XElement.Join our .Load () when you want to load everything under the top-level element. It used T-SQL to query the data to query the database and some other syntax for querying the other data source. ". To handle this concurrency conflicts. It is a part of . It has full type checking at compile-time and IntelliSense support in Visual Studio. Ans. LINQ is not a good way for bulk insert and update operations. you have to recompile it and redeploy its dll to the server.NET Framework 1.NET Framework since . XElement and XDocument are the classes defined with in System. 3.NET Training Programs in Delhi/Noida 2.dotnet-tricks. KeepCurrentValues . "Shailendra Chauhan")) ). since it used the . It used LINQ to query the data which provides the uniform programming model (means common query syntax) to query the various data sources. a conflict will occur. new XElement("Author". XElement and XDocument are very similar in function.This option will remains the LINQ object values as it is and does not push the new values from the database in to the LINQ object. Call Us : +91-9871749695 LINQ is not the good for writing complex queries as compared to stored procedures. 2. www.NET Framework since . What is difference between ADO.NET Framework 3. new XElement("Name". When multiple users are updating the same record at the same time. How can you handle concurrency in LINQ to SQL? Ans.5 We can use context for database connectivity. Q54. While XDocument class represents an entire XML document with all associated properties.NET and Entity Framework: ADO.NET Interview FAQ"). 4.NET LINQ to SQL It is a part of . Easy to debug and cause syntax errors at compile-time.Load()? Ans. For Example: XDocument doc = new XDocument(new XElement("Book". since it used the T-SQL to query the database. OverwriteCurrentValues .0 SqlConnection/OleDbConnection is used for database connectivity.NET Framework languages like C# and VB.Linq namespace. What is difference between XElement. Use XDocument. Difficult to debug and cause syntax errors at run-time. Q51. If you have done some changes in your query.com Handy Tricks For Beginners & Professionals 35 . XElement class represents an XML fragment. LINQ provides you following three ways.This option will replace the LINQ object values with the database values. Q52.Xml. Performance is degraded if you don't write the LINQ query correctly. but not interchangeable when you are loading a document from a data source. Q53.NET and LINQ to SQL? There are following differences between ADO. In this case changed properties of an object/entity remains as it is but the properties which are not changed are fetched from the database and replaced.Linq namespace. try { // TO DO: db. Always: . Never: .} get{return _CustomerID. To handle concurrency conflicts. [Column(DbType = "nvarchar(50)".NET Training Programs in Delhi/Noida Call Us : +91-9871749695 3.ChangeConflicts) { changeconf. wrap the code with in a try block and catch the ChangeConflictException by using catch block and iterate through the ChangeConflicts collection to resolve the conflict as shown below: DataContext db = new DataContext().Never)] public string CustomerID { set{CustomerID = value. } catch (ChangeConflictException ex) { foreach (ObjectChangeConflict changeconf in db.This option will always check for concurrency conflicts. 3.This option will never check for concurrency conflicts.SubmitChanges(ConflictMode. 2. All these options are available in RefereshMode enum which exist in System. WhenChanged: . UpdateCheck = UpdateCheck.} } www. you can also handle concurrency at field level and this is the best way provided by the LINQ. KeepChanges .Resolve(RefreshMode.Data.Join our .dotnet-tricks.OverwriteCurrentValues).com Handy Tricks For Beginners & Professionals 36 .This option will check for concurrency conflicts when the field’s value has been changed. } } Q55. In LINQ to SQL. To achieve this you need to define UpdateCheck attribute at field level and it has the following options: 1. How can you handle concurrency at field level in LINQ to SQL? Ans.ContinueOnConflict).
Copyright © 2024 DOKUMEN.SITE Inc.