Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts

Saturday, 21 January 2023

LINQ query related questions

 Find nth max salary using linq

I have a collection of Employee Data. 

//7000,6000,5500,5000
List<Employee> employees = new List<Employee>()
{
new Employee { Id = 1, UserName = "Anil" , Salary = 5000},
new Employee { Id = 2, UserName = "Sunil" , Salary = 6000},
new Employee { Id = 3, UserName = "Lokesh" , Salary = 5500},
new Employee { Id = 4, UserName = "Vinay" , Salary = 7000},
new Employee { Id = 5, UserName = "Vijay" , Salary = 7000},
new Employee { Id = 6, UserName = "vikas" , Salary = 6000}
};

See the below query example. I am finding 2nd max Salary.

Query Example 1:

var employee = Employees.OrderByDescending(e => e.Salary).Skip(1).First();                              

  var result = employees.OrderByDescending(x => x.Salary)
  .Select(x => x.Salary).Distinct().Take(2)
  .Skip(2 - 1).FirstOrDefault();
Console.WriteLine(result);

Query Example 2:

If multiple employees may have equal salary and you wish to return an IEnumerable of all the employees with the second-highest salary you could do:

var result = employees
      .GroupBy(e => e.Salary)
      .OrderByDescending(e=> e.Key)
      .Skip(1)
      .First();
Console.WriteLine(result.Key);


Find 2nd and 3rd max Number from below array using Linq

 int[] numbers = { 1, 4, 2, 6, 3, 7, 9, 0 };

var secondMaxNumber = (from n in numbers orderby n descending select n)
.Take(2).LastOrDefault();
var thirdMaxNumber = (from n in numbers orderby n descending select n).Distinct()
.Skip(2).FirstOrDefault();

Console.WriteLine(secondMaxNumber); //7
Console.WriteLine(thirdMaxNumber);  //6


Continue Reading →

Saturday, 30 December 2017

SingleOrDefault Vs FirstOrDefault

 SingleOrDefault() Vs. FirstOrDefault() in LINQ Query


Single() / SingleOrDefault()
First () / FirstOrDefault()
Single() - There is exactly 1 result, an exception is thrown if no result is returned or more than one result. 
SingleOrDefault() – Same as Single(), but it can handle the null value.
First() - There is at least one result, an exception is thrown if no result is returned.
FirstOrDefault() - Same as First(), but not thrown any exception or return null when there is no result.
Single() asserts that one and only one element exists in the sequence.
First() simply gives you the first one.
When to use
Use Single / SingleOrDefault() when you sure there is only one record present in database or you can say if you querying on database with help of primary key of table.
When to use
Developer may use First () / FirstOrDefault() anywhere,  when they required single value from collection or database.
Single() or SingleOrDefault() will generate a regular TSQL like "SELECT ...".
The First() or FirstOrDefault() method will generate the TSQL statment like "SELECT TOP 1..."
In the case of Fist / FirstOrDefault, only one row is retrieved from the database so it performs slightly better than single / SingleOrDefault. such a small difference is hardly noticeable but when table contain large number of column and row, at this time performance is noticeable.
Continue Reading →

Monday, 10 July 2017

Select and SelectMany in LINQ

Select and SelectMany are projection operators. Select operator is used to select value from a collection and SelectMany operator is used to select values from a collection of collection i.e. nested collection.

Example: 

class Employee
{
 public string Name { get; set; }
 public List<string> Skills { get; set; }
}
 
class Program
{
 static void Main(string[] args)
 {
 List<Employee> employees = new List<Employee>();
 Employee emp1 = new Employee { Name = "Deepak", Skills = new List<string> { "C", "C++", "Java" } };
 Employee emp2 = new Employee { Name = "Karan", Skills = new List<string> { "SQL Server", "C#", "ASP.NET" } };
 
 Employee emp3 = new Employee { Name = "Lalit", Skills = new List<string> { "C#", "ASP.NET MVC", "Windows Azure", "SQL Server" } };
 
 employees.Add(emp1);
 employees.Add(emp2);
 employees.Add(emp3);
 
 // Query using Select()
 IEnumerable<List<String>> resultSelect = employees.Select(e=> e.Skills);
 
 Console.WriteLine("**************** Select ******************");
 
 // Two foreach loops are required to iterate through the results
 // because the query returns a collection of arrays.
 foreach (List<String> skillList in resultSelect)
 {
 foreach (string skill in skillList)
 {
 Console.WriteLine(skill);
 }
 Console.WriteLine();
 }
 
 // Query using SelectMany()
 IEnumerable<string> resultSelectMany = employees.SelectMany(emp => emp.Skills);
 
 Console.WriteLine("**************** SelectMany ******************");
 
 // Only one foreach loop is required to iterate through the results 
 // since query returns a one-dimensional collection.
 foreach (string skill in resultSelectMany)
 {
 Console.WriteLine(skill);
 }
 
 Console.ReadKey();
 }
}
 
/* Output
 
**************** Select ******************
 
C
C++
Java
 
SQL Server
C#
ASP.NET
 
C#
ASP.NET MVC
Windows Azure
SQL Server
 
**************** SelectMany ******************
 
C
C++
Java
SQL Server
C#
ASP.NET
C#
ASP.NET MVC
Windows Azure
SQL Server
*/
Continue Reading →

Wednesday, 11 March 2015

Inner Join, Cross Join and Left Outer Join With LINQ to SQL

The join operations in this article are done using COURSE and STUDENT tables. So now I am going to explain the joins to be done using LINQ to SQL step-by-step.
Step 1: Create COURSE and STUDENT Tables in the database as in the following:
 
 
CREATE TABLE COURSE
 
(
     course_id int IDENTITY(1,1) PRIMARY KEY
,
 
    course_name nvarchar(70) NOT NULL,
 
    course_desc nvarchar(255) NULL,
 
    modified_date date NULL,
 
)
 
CREATE TABLE STUDENT
 
(
 
    student_id int IDENTITY(1,1) PRIMARY KEY,
 
    student_name nvarchar(70),
 
    student_city nvarchar(30),
 
    course_id int NOT NULL
 
)
 

Step 2: Define foreign key constraints on the STUDENT table as in the following:
 
 
ALTER TABLE STUDENT
 
ADD CONSTRAINT [FK_STUDENT_COURSE] FOREIGN KEY (course_id)REFERENCES COURSE(course_id)
 

Step 3: Create Data Layer
 
Create a dbml file (Operation.dbml in this article) and using the Object Relation Designer create a data context class for the STUDENT and COUSRE tables.


In the above figure we drag and drop both the COURSE and STUDENT tables onto the designer map of the Operation.dbml file and that shows the relationship between the COURSE and STUDENT tables.
 
Step 4: Inner Join in LINQ to SQL
 
 
OperationDataContext odDataContext = new OperationDataContext();
 var studentInfo = from student in odDataContext.STUDENTs
 join course in odDataContext.COURSEs
 on student.course_id equals       course.course_id
 select new { student.student_name, student.student_city, course.course_name, course.course_desc };
 

In the above code we join the STUDENT table and the COURSE table using the "join" keyword and using the "on" keyword join the tables by the course_id field of both tables. It returns all rows with a common course_id in both tables.
 
Step 5: Cross Join in LINQ to SQL
 
 
OperationDataContext odDataContext = new OperationDataContext();
 var studentInfo = from student in odDataContext.STUDENTs
 from course in odDataContext.COURSEs
 select new { student.student_name, student.student_city, course.course_name, course.course_desc };
 

In the above code we are doing a cross-join on both the STUDENT table and the COURSE table. We get all rows from both tables and the total rows are STUDENT table rows * COURSE table rows.
 
Step 6: Left Join in LINQ to SQL
 
 
OperationDataContext odDataContext = new OperationDataContext();
 var courseInfo = from course in odDataContext.COURSEs
 join student in odDataContext.STUDENTs
 on course.course_id equals  student.course_id into studentInfo
 from students in studentInfo.DefaultIfEmpty()
 select new 
 {
     STUDENTNAME = (students.student_name == null)? NULL":students.student_name, 
     STUDENTCITY = (students.student_city == null)? "NULL":students.student_city,
     COURSENAME = course.course_name, 
     COUSREDESCRIPTION = course.course_desc 
 };
 

In above code we are doing a Left Join. Here the left table is COURSE. So it will return all rows from the course table not depends STUDENT table course_id field. If the course_id field value is in the COURSE table but not in the STUDENT table then in the row course_name and course_desc fields will show and student_name and student_city fields will show NULL. Here the output will be the total number of rows in the COURSE table. 

I found one more helpfull link  Click here.

Continue Reading →

Thursday, 11 December 2014

Lazy Loading and Eager Loading

~Difference between Lazy Loading and Eager Loading~

In LINQ and Entity Framework, you have Lazy Loading and Eager Loading for loading the related entities of an entity. In this article you will learn the differences between these two loading.

Lazy/Deferred Loading

       In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.

For Example:

var query = context.Categories.Take(3); // Lazy loading

foreach (var Category in query)
{
 Console.WriteLine(Category.Name);
 foreach (var Product in Category.Products)
 {
 Console.WriteLine(Product.ProductID);
 }

 }

Generated SQL Query will be:

SELECT TOP (3)
[c].[CatID] AS [CatID],
[c].[Name] AS [Name],
[c].[CreatedDate] AS [CreatedDate]
FROM [dbo].[Category] AS [c]
GO

-- Region Parameters
DECLARE @EntityKeyValue1 Int = 1
-- EndRegion
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[Name] AS [Name],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[CatID] AS [CatID],
[Extent1].[EntryDate] AS [EntryDate],
[Extent1].[ExpiryDate] AS [ExpiryDate]
FROM [dbo].[Product] AS [Extent1]
WHERE [Extent1].[CatID] = @EntityKeyValue1
GO

-- Region Parameters
DECLARE @EntityKeyValue1 Int = 2
-- EndRegion
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[Name] AS [Name],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[CatID] AS [CatID],
[Extent1].[EntryDate] AS [EntryDate],
[Extent1].[ExpiryDate] AS [ExpiryDate]
FROM [dbo].[Product] AS [Extent1]
WHERE [Extent1].[CatID] = @EntityKeyValue1
GO

-- Region Parameters
DECLARE @EntityKeyValue1 Int = 3
-- EndRegion
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[Name] AS [Name],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[CatID] AS [CatID],
[Extent1].[EntryDate] AS [EntryDate],
[Extent1].[ExpiryDate] AS [ExpiryDate]
FROM [dbo].[Product] AS [Extent1]
WHERE [Extent1].[CatID] = @EntityKeyValue1


 In above example, you have 4 SQL queries which means calling the database 4 times, one for the Categories and three times for the Products associated to the Categories. In this way, child entity is populated when it is requested.
       You can turn off the lazy loading feature by setting LazyLoadingEnabled property of the ContextOptions on context to false. Now you can fetch the related objects with the parent object in one query itself.

context.ContextOptions.LazyLoadingEnabled = false;

Eager loading
       In case of eager loading, related objects (child objects) are loaded automatically with its parent object. To use Eager loading you need to use Include() method.

For Example:
var query = context.Categories.Include("Products").Take(3); // Eager loading

 foreach (var Category in query)
 {
 Console.WriteLine(Category.Name);
 foreach (var Product in Category.Products)
 {
 Console.WriteLine(Product.ProductID);
 }
 }

Generated SQL Query will be:

SELECT [Project1].[CatID] AS [CatID],
 [Project1].[Name] AS [Name],
 [Project1].[CreatedDate] AS [CreatedDate],
 [Project1].[C1] AS [C1],
 [Project1].[ProductID] AS [ProductID],
 [Project1].[Name1] AS [Name1],
 [Project1].[UnitPrice] AS [UnitPrice],
 [Project1].[CatID1] AS [CatID1],
 [Project1].[EntryDate] AS [EntryDate],
 [Project1].[ExpiryDate] AS [ExpiryDate]
 FROM (SELECT
 [Limit1].[CatID] AS [CatID],
 [Limit1].[Name] AS [Name],
 [Limit1].[CreatedDate] AS [CreatedDate],
 [Extent2].[ProductID] AS [ProductID],
 [Extent2].[Name] AS [Name1],
 [Extent2].[UnitPrice] AS [UnitPrice],
 [Extent2].[CatID] AS [CatID1],
 [Extent2].[EntryDate] AS [EntryDate],
 [Extent2].[ExpiryDate] AS [ExpiryDate],
 CASE WHEN ([Extent2].[ProductID] IS NULL) THEN CAST(NULL AS int)
ELSE 1 END AS [C1]
FROM (SELECT TOP (3) [c].[CatID] AS [CatID], [c].[Name] AS [Name], [c].[CreatedDate] AS [CreatedDate]
 FROM [dbo].[Category] AS [c] )
AS [Limit1]
 LEFT OUTER JOIN [dbo].[Product] AS [Extent2]
ON [Limit1].[CatID] = [Extent2].[CatID]) AS [Project1]
 ORDER BY [Project1].[CatID] ASC, [Project1].[C1] ASC

In above example, you have only one SQL queries which means calling the database only one time, for the Categories and the Products associated to the Categories. In this way, child entity is populated with parent entity.

I hope you will enjoy the tips while programming with LINQ and Entity Framework. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Continue Reading →

Tuesday, 9 December 2014

LINQ vs Stored Procedure

Comparing LINQ with Stored Procedure
LINQ provide you common query syntax to query various data sources like SQL Server, Oracle, DB2, WebServices, XML and Collection etc. LINQ also has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET framework languages like C# and VB.NET.


On the other hand a stored procedure is a pre-compiled set of one or more SQL statements that is stored on RDBMS (SQL Server, Oracle, DB2 and MySQL etc.). The main advantage of stored procedures is that they are executed on the server side and perform a set of actions, before returning the results to the client side. This allows a set of actions to be executed with minimum time and also reduce the network traffic.

A brief comparison of LINQ and Stored Procedure
  1. 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. Hence, when a stored procedure is being executed next time, the database used the cached execution plan to execute that stored procedure.
  2. LINQ has full type checking at compile-time and Intellisense support in Visual Studio as compared to stored procedure. This powerful feature helps you to avoid run-time errors.
  3. LINQ allows debugging through .NET debugger as compared to stored procedure.
  4. LINQ also supports various .NET framework features like multi –threading as compared to stored procedures.
  5. 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.
  6. Stored procedure is a best way for writing complex queries as compared to LINQ.
  7. Deploying LINQ based application is much easy and simple as compared to stored procedures based. Since in case of stored procedures, you need to provide a SQL script for deployment but in case of LINQ everything gets complied into the DLLs. Hence you need to deploy only DLLs.
Limitation of LINQ over Stored Procedures
  1. LINQ query is compiled each and every time while stored procedures re-used the cached execution plan to execute. Hence, LINQ query takes more time in execution as compared to stored procedures.
  2. LINQ is not the good for writing complex queries as compared to stored procedures.
  3. LINQ is not a good way for bulk insert and update operations.
  4. Performance is degraded if you don't write the LINQ query correctly.
  5. If you have done some changes in your query, you have to recompile it and redeploy its DLLs to the server.
What do you think?
I hope you will enjoy LINQ and stored procedure while playing with database. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
Continue Reading →

Tuesday, 25 November 2014

Ordering data in LINQ queries by more than one column

In this post, I am going to show how to do ordering when you require to order data by using multiple columns.
By using .Orderby(x=>x.Columnname) in a LINQ query, we can easily order data in a source collection. Most new developers make use of the same function twice .Orderby(x=>x.Columnname).Orderby(x=>x.Columnname) and thinks that will do the ordering in multiple columns.

IEnumerable<Employeeemp = dc.Employees
                                 .OrderBy(x => x.Name)
                                 .OrderBy(x => x.Desc);

But it always does the order by the column you specified in the last OrderBy() method. 

Following are two solutions to achieve: 
Solution 1

 Always make use of ThenBy() after OrderBy() because OrderBy() returns an IOrderedEnumerable which then exposes the methods ThenBy() and ThenByDescending(). This means that we can OrderBy on multiple fields by chaining OrderBy() and ThenBy() together.

IEnumerable<Employeeemp = dc.Employees
                                  .OrderByx => x.Name)
                                 .ThenBy((x => x.Desc);

Solution 2
If you don't want to go for Lambda expression, you can easily achieve multiple ordering:

var emp = from e in dc.Employees
          orderby e.Namee.Desc
          select e;

As you can see, in the above statement, after order by, you can add multiple columns and do the
ordering on the multiple columns.


Continue Reading →

Saturday, 18 October 2014

IEnumerable vs IQueryable

Many  developers gets confused between IEnumerable and IQueryable. When it comes to writing code, both looks very similar. However there are many difference between them which needs to be taken care of while writing code. Both have some intended usability scenarios for which they are made.

The first important point to remember is “IQueryable” interface inherits from “IEnumerable”, so whatever “IEnumerable” can do, “IQueryable” can also do.



There are many differences but let us discuss about the one big difference which makes the biggest difference. “IQueryable” interface is useful when your collection is loaded using LINQ or Entity framework and you want to apply filter on the collection.
Consider the below simple code which uses “IEnumerable” with entity framework. It’s using a “where” filter to get records whose “EmpId” is “2”.

IEnumerable<Employee> emp = ent.Employees;

IEnumerable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>();

This where filter is executed on the client side where the “IEnumerable” code is. In other words, all the data is fetched from the database and then at the client it scans and gets the record with “EmpId” is “2”.

But now see the below code we have changed “IEnumerable” to “IQueryable”.

IQueryable<Employee> emp = ent.Employees;

IEnumerable<Employee> temp = emp.Where(x => x.Empid == 2).ToList<Employee>();

In this case, the filter is applied on the database using the “SQL” query. So the client sends a request and on the server side, a select query is fired on the database and only necessary data is returned.


So the difference between “IQueryable” and “IEnumerable” is about where the filter logic is executed. One executes on the client side and the other executes on the database.
So if you are working with only in-memory data collection “IEnumerable” is a good choice but if you want to query data collection which is connected with database, “IQueryable” is a better choice as it reduces network traffic and uses the power of SQL language.



Below lists the differences between them based on their properties :
IEnumerable IQueryable
NamespaceSystem.Collections NamespaceSystem.Linq Namespace
Derives fromNo base interfaceDerives from IEnumerable
Deferred ExecutionSupportedSupported
Lazy LoadingNot SupportedSupported
How does it workWhile querying data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data. Hence does more work and becomes slow.While querying data from database,
IQueryable execute select query on
server side with all filters. Hence does
less work and becomes fast.
Suitable forLINQ to Object and LINQ to XML queries.LINQ to SQL queries.
Custom QueryDoesn’t supports.Supports using CreateQuery and
Execute methods.
Extension mehtod
parameter
Extension methods supported in IEnumerable takes functional objects.Extension methods supported in
IEnumerable takes expression objects
i.e. expression tree.
When to usewhen querying data from in-memory collections like List, Array etc.when querying data from out-memory
(like remote database, service)
collections.
Best UsesIn-memory traversalPaging
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives