0% found this document useful (0 votes)
31 views24 pages

LINQ

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views24 pages

LINQ

Uploaded by

thirosul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

LINQ

LINQ stands for Language Integrated Query, a Microsoft .NET Framework that provides a
standardized way to query data from various data sources using a common syntax within
programming languages like C# or VB.

LINQ allows developers to write queries to retrieve, manipulate, and transform data from
different data sources, such as databases, collections, XML, and In-Memory objects.

Architecture of LINQ
The architecture of LINQ is 3-layered architecture. In which the topmost layer contains
language extension and the bottom layer contains data sources that generally object
implementing IEnumerable <T> or IQueryable <T> generic interfaces. The architecture of
the LINQ is as shown in the below image:
 The main purpose behind creating LINQ is, before C# 3.0 we use for loop,
foreach loop, or delegates traverse a collection to find a specific object, but
the disadvantage of using these methods for finding an object is you need to
write a large sum of code to find an object which is more time-consuming and
make your program less readable. So to overcome these problems LINQ
introduced. Which perform the same operation in a few numbers of lines and
make your code more readable and also you can use the same code in other
programs.
 It also provides full type checking at compile time, it helps us to detect the
error at the runtime, so that we can easily remove them.
 LINQ is it is simple, well-ordered, and high-level language than SQL
 You can also use LINQ with C# array and collections. It gives you a new
direction to solve the old problems in an effective manner.
 With the help of LINQ you can easily work with any type of data source like
XML, SQL, Entities, objects, etc. A single query can work with any type of
database no need to learn different types of languages.
 LINQ supports query expression, Implicitly typed variables, Object and
collection initializers, Anonymous types, Extension methods, and Lambda
expressions.

. The following is a list of some of the features:


 Query Expression
 Object and Collection Initializer
 Implicitly Typed variable
 Anonymous types
 Lambda Expression

Query Expression

A Query is a set of instructions that describe what the data is to retrieve from a given data
source. And a Query Expression is a query, expressed in query syntax. A LINQ Query
Expression is also very similar to SQL. A LINQ Query Expression contains the following
three (3) clauses:
 From
 Where
 Select
From: specifies the data source
Where: applies data filtration
Select: specifies the returned elements

Example:-

1. var query = from n in numbers


2. where (n/2)==0
3. select n;
Object and Collection Initializer
 The Object Initializer helps to assign some value to assessable fields or properties of
an object at creation time, without invoking a constructor.
 This feature enables the specific argument for a constructor.
 Objects and collection initializers make initilization of objects possible without
explicitly calling a constructor for the object.
 This is typically used in a query expression when they project the source data into a
new data type.

Example

1. Student studentQuery= new Student{ name= "Rajeev" , Address = "Pasir Ris" }

Implicitly Typed variable


 We can use local variables as an inferred "type" of var instead of an explicit type.
The var keyword instructs the compiler to infer the type of the variable from the
expression on the right side of the initialization statement
 . The inferred type may be a built-in type, an anonymous type, a user-defined type, or
a type defined in the .NET Framework class library.
 A variable decleared as a var are just as strongly-typed as variables whose type you
specify explicitly.
 The use of var makes it possible to create anonymous types.

Example

1. var num = 5;
2. var str="Rajeev";
3. var query = from s in StringArray
4. where s[0] == 'm'
5. select s;

Anonymous types
 Anonymous types are class types that derive directly from an object and that cannot
be cast to any type except objects.
 It is not different from any other reference type.
 The complier provides a name for each anonymous type
 . Anonymous types are typically used in the select clause of a query expression to
return a subset of properties from each object in the source sequence.
 Anonymous types contains one or more public read-only properties.
 The expression that is used to initialized a property cannot be null.

Example

1. select new { name= student.Name, Address= student.Address};

Lambda Expression
 A lambda expression is an anonymous function that we can use to create delegates or
expression tree types.
 By using lambda expressions, we can write local functions that can be passed as
arguments or returned as the value of function calls
 . Lambda expressions are particularly helpful for writing LINQ query expressions.
 A lambda expression is an inline function that uses the => operator to separate input
parameters from the function body and can be converted at compile time to a delegate
or an expression tree
 . In LINQ programming, you will encounter lambda expressions when you make
direct method calls to the standard query operators.

Example

1. int[] numbers = { 25, 7, 6, 4, 12, 58, 67, 92, 42, 60 };


2. int oddNumbers = numbers.Count(n => n % 2 == 1);

a. Query Syntax

 Definition: A syntax similar to SQL that allows you to write queries in a more
readable way.
 Usage: Useful for complex queries that benefit from a structured format.

Example:

var query = from n in numbers


where n > 2
select n;

b. Method Syntax

 Definition: Uses method calls with extension methods.


 Usage: Often preferred for chaining operations, providing more flexibility and
composability.

Example:

a. Query Syntax

 Definition: A syntax similar to SQL that allows you to write queries in a more
readable way.
 Usage: Useful for complex queries that benefit from a structured format.

Example:

var numbers = new List<int> { 1, 2, 3, 4, 5 };


var evenNumbers = from n in numbers

where n % 2 == 0

select n;

foreach (var num in evenNumbers)

Console.WriteLine(num);

b. Method Syntax

 Definition: Uses method calls with extension methods.


 Usage: Often preferred for chaining operations, providing more flexibility and
composability.

Example

var evenNumbers = numbers.Where(n => n % 2 == 0);

foreach (var num in evenNumbers)

Console.WriteLine(num);

LINQ expression

Take the reference of System.Linq.Expressions namespace and use an


Expression<TDelegate> class to define an Expression. Expression<TDelegate>
requires delegate type Func or Action.

For example, you can assign lambda expression to the isTeenAger variable of Func
type delegate, as shown below:

using System;
using System.Linq.Expressions;

public class Program


{
public static void Main()
{
Expression<Func<Student, bool>> isTeenAgerExpr = s => s.Age > 12 && s.Age < 20;

//compile Expression using Compile method to invoke it as Delegate


Func<Student, bool> isTeenAger = isTeenAgerExpr.Compile();

//Invoke
bool result = isTeenAger(new Student(){ StudentID = 1, StudentName = "Steve", Age =
14});

Console.WriteLine(result);
}
}

public class Student{

public int StudentID { get; set; }


public string StudentName { get; set; }
public int Age { get; set; }
}

Output ;- true

LinQ pattern

1. Filtering with Where

Explanation:

 The Where method is used to filter a collection based on a specified


predicate (a function that returns a boolean).
 It iterates through each element and applies the condition, returning a new
collection with only the elements that meet the criteria.
 Commonly used to filter data based on user input or specific conditions,
like finding records that match a certain criteria.

Program

using System;

using System.Collections.Generic;

using System.Linq;

namespace LINQExamples

// Class representing a person

public class Person

public string Name { get; set; }

public int Age { get; set; }

public class Program

public static void Main()

List<Person> people = new List<Person>

new Person { Name = "Alice", Age = 30 },

new Person { Name = "Bob", Age = 25 },


new Person { Name = "Charlie", Age = 35 },

new Person { Name = "Diana", Age = 18 },

new Person { Name = "Edward", Age = 22 }

};

// Example 1: Filtering

var evenAges = people.Where(p => p.Age % 2 == 0).ToList();

Console.WriteLine("People with even ages:");

foreach (var person in evenAges)

Console.WriteLine($"{person.Name}, Age: {person.Age}");

Output ;-
People with even ages:

Alice, Age: 30

Diana, Age: 18

Edward, Age: 22

2. Projection with Select

Explanation:

 The Select method transforms each element of a collection into a new form, defined by the
projection function.
 It creates a new collection where each element is the result of applying the transformation to
the original element.
 Useful when you want to create a new collection with a different type or shape (e.g.,
extracting specific properties from objects).

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQExamples
{
// Class representing a person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

// Main class for LINQ operations


public class Program
{
public static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 },
new Person { Name = "Diana", Age = 18 },
new Person { Name = "Edward", Age = 22 }
};

// Example 2: Projection
var names = people.Select(p => p.Name).ToList();
Console.WriteLine("\nNames of people:");
Console.WriteLine(string.Join(", ", names));
}
}
}

Output:-
Names of people:
Alice, Bob, Charlie, Diana, Edward

3. Ordering with OrderBy and OrderByDescending

Explanation:

 OrderBy sorts the elements of a collection in ascending order based on a specified key.
 OrderByDescending does the same but in descending order.
 The sorting is stable, meaning that elements that are equal in the sort key retain their original
order.
 Essential for displaying data in a user-friendly format, such as sorting names alphabetically
or prices from low to high.

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQExamples
{
// Class representing a person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}

// Class representing an order

// Main class for LINQ operations


public class Program
{
public static void Main()
{
List<Person> people = new List<Person>
{
new Person { Name = "Alice", Age = 30 },
new Person { Name = "Bob", Age = 25 },
new Person { Name = "Charlie", Age = 35 },
new Person { Name = "Diana", Age = 18 },
new Person { Name = "Edward", Age = 22 }
};

// Example 3: Ordering
var sortedByAge = people.OrderBy(p => p.Age).ToList();
Console.WriteLine("\nPeople sorted by age:");
foreach (var person in sortedByAge)
{
Console.WriteLine($"{person.Name}, Age: {person.Age}");
}

}
}
}

Output ;-

People sorted by age:


Diana, Age: 18
Edward, Age: 22
Bob, Age: 25
Alice, Age: 30
Charlie, Age: 35
4. Grouping with GroupBy
Explanation:

 The GroupBy method organizes a collection into groups based on a specified key.
 Each group is represented as an IGrouping<TKey, TElement> where TKey is the type of the
key and TElement is the type of elements in the group.
 Useful for categorizing data (e.g., grouping sales by product category or customers by
location).

using System;

using System.Collections.Generic;

using System.Linq;

namespace LINQExamples

// Class representing a person

public class Person

public string Name { get; set; }

public int Age { get; set; }

// Main class for LINQ operations

public class Program

{
public static void Main()

List<Person> people = new List<Person>

new Person { Name = "Alice", Age = 30 },

new Person { Name = "Bob", Age = 25 },

new Person { Name = "Charlie", Age = 35 },

new Person { Name = "Diana", Age = 18 },

new Person { Name = "Edward", Age = 22 }

};

// Example 4: Grouping

var groupedByAge = people.GroupBy(p => p.Age);

Console.WriteLine("\nPeople grouped by age:");

foreach (var group in groupedByAge)

Console.WriteLine($"Age: {group.Key}");

foreach (var person in group)

Console.WriteLine($" {person.Name}");

Output;-
People grouped by age:

Age: 30

Alice

Age: 25

Bob

Age: 35

Charlie

Age: 18

Diana

Age: 22

Edward

5. Joining Collections with Join

Explanation:

 The Join method combines two collections based on a shared key, producing a new collection
of results.
 It requires both collections to be related by a common key and produces pairs of elements
from each collection that match based on the key.

 Commonly used when dealing with related datasets, like merging customer information with
their orders or invoices.

1. Inner Join

An inner join returns only the records that have matching values in both collections.
2. Left Outer Join

A left outer join returns all records from the left collection and the matched records from the
right collection. If there’s no match, the result is null on the right side.

3. Right Outer Join

A right outer join is not directly supported in LINQ syntax, but you can achieve it by
swapping the roles of the collections. It returns all records from the right collection and the
matched records from the left.

4. Full Outer Join

A full outer join returns all records when there is a match in either left or right collection.
This isn't directly supported in LINQ but can be simulated by combining left and right outer
joins.

using System;

using System.Collections.Generic;

using System.Linq;

namespace JoinExamples

class Program

public class Person

public int Id { get; set; }

public string Name { get; set; }

public class Order

public int Id { get; set; }


public int CustomerId { get; set; }

static void Main()

List<Person> people = new List<Person>

new Person { Id = 1, Name = "Alice" },

new Person { Id = 2, Name = "Bob" },

new Person { Id = 3, Name = "Charlie" }

};

List<Order> orders = new List<Order>

new Order { Id = 1, CustomerId = 1 },

new Order { Id = 2, CustomerId = 2 },

new Order { Id = 3, CustomerId = 4 } // No corresponding person

};

// 1. Inner Join

var innerJoin = from p in people

join o in orders on p.Id equals o.CustomerId

select new { p.Name, o.Id };

Console.WriteLine("Inner Join Results:");

foreach (var item in innerJoin)


{

Console.WriteLine($"Customer: {item.Name}, Order ID: {item.Id}");

// 2. Left Outer Join

var leftOuterJoin = from p in people

join o in orders on p.Id equals o.CustomerId into gj

from subOrder in gj.DefaultIfEmpty()

select new { p.Name, OrderId = subOrder?.Id };

Console.WriteLine("\nLeft Outer Join Results:");

foreach (var item in leftOuterJoin)

Console.WriteLine($"Customer: {item.Name}, Order ID: {item.OrderId ?? -1}");

// 3. Right Outer Join (simulated by swapping)

var rightOuterJoin = from o in orders

join p in people on o.CustomerId equals p.Id into gj

from subPerson in gj.DefaultIfEmpty()

select new { CustomerName = subPerson?.Name ?? "No Customer", o.Id


};

Console.WriteLine("\nRight Outer Join Results:");

foreach (var item in rightOuterJoin)

Console.WriteLine($"Customer: {item.CustomerName}, Order ID: {item.Id}");


}

// 4. Full Outer Join (simulated)

var left = from p in people

join o in orders on p.Id equals o.CustomerId into gj

from subOrder in gj.DefaultIfEmpty()

select new { p.Name, OrderId = subOrder?.Id };

var right = from o in orders

join p in people on o.CustomerId equals p.Id into gj

from subPerson in gj.DefaultIfEmpty()

select new { CustomerName = subPerson?.Name ?? "No Customer", o.Id };

var fullOuterJoin = left.Union(right.Select(x => new { Name = x.CustomerName,


OrderId = x.OrderId }));

Console.WriteLine("\nFull Outer Join Results:");

foreach (var item in fullOuterJoin)

Console.WriteLine($"Customer: {item.Name ?? "No Customer"}, Order ID:


{item.OrderId ?? -1}");

}
6. Aggregating with Sum, Average, Min, Max, and Count

Explanation:

 Aggregate functions perform calculations on collections and return a single value.


 Sum computes the total, Average computes the mean, Min and Max find the smallest and
largest values, respectively, while Count gives the number of elements.
 Useful in reporting scenarios where summaries of data are needed, such as total sales or
average scores.

using System;

using System.Collections.Generic;

using System.Linq;

namespace AggregationExamples

class Program

public class Person

public string Name { get; set; }

public int Age { get; set; }

public decimal Salary { get; set; }

static void Main()

List<Person> people = new List<Person>

new Person { Name = "Alice", Age = 30, Salary = 60000 },


new Person { Name = "Bob", Age = 25, Salary = 50000 },

new Person { Name = "Charlie", Age = 35, Salary = 70000 },

new Person { Name = "Diana", Age = 28, Salary = 55000 },

new Person { Name = "Edward", Age = 22, Salary = 45000 }

};

// 1. Sum

var totalSalary = people.Sum(p => p.Salary);

Console.WriteLine($"Total Salary: {totalSalary}");

// 2. Average

var averageAge = people.Average(p => p.Age);

Console.WriteLine($"Average Age: {averageAge}");

// 3. Min

var minSalary = people.Min(p => p.Salary);

Console.WriteLine($"Minimum Salary: {minSalary}");

// 4. Max

var maxAge = people.Max(p => p.Age);

Console.WriteLine($"Maximum Age: {maxAge}");

// 5. Count

var totalPeople = people.Count();

Console.WriteLine($"Total Number of People: {totalPeople}");

}
}

Output:-

Total Salary: 280000

Average Age: 28

Minimum Salary: 45000

Maximum Age: 35

Total Number of People: 5

7. Getting Distinct Values with Distinct

Explanation:

 The Distinct method filters a collection to remove duplicate elements.


 It returns a new collection with only unique elements based on default equality or a
custom equality comparer.
 Ideal for situations where you need to ensure unique values, such as retrieving distinct
categories or tags from a list.

using System;

using System.Collections.Generic;

using System.Linq;

namespace LINQExamples

// Class representing a person

public class Person

public string Name { get; set; }

public int Age { get; set; }

}
// Class representing an order

// Main class for LINQ operations

public class Program

public static void Main()

List<Person> people = new List<Person>

new Person { Name = "Alice", Age = 30 },

new Person { Name = "Bob", Age = 25 },

new Person { Name = "Charlie", Age = 35 },

new Person { Name = "Diana", Age = 18 },

new Person { Name = "Edward", Age = 22 } }

// Example 3: Ordering

var distinctAges = people.Select(p => p.Age).Distinct().ToList();

Console.WriteLine("\nDistinct Ages:");

foreach (var age in distinctAges)

Console.WriteLine(age);

Output:-
Distinct Ages:

30

25

35

18

22

8. Combining Queries
Explanation:

 LINQ allows you to chain multiple methods together to build complex queries in a
readable manner.
 You can combine filtering, sorting, and projection in a single expression, which is
efficient and concise.
 When you need to perform multiple operations on data sequentially, such as filtering,
then sorting, and finally selecting specific properties.

. using System;

using System.Collections.Generic;

using System.Linq;

namespace LINQExamples

// Class representing a person

public class Person

public string Name { get; set; }

public int Age { get; set; }

// Class representing an order


// Main class for LINQ operations

public class Program

public static void Main()

List<Person> people = new List<Person>

new Person { Name = "Alice", Age = 30 },

new Person { Name = "Bob", Age = 25 },

new Person { Name = "Charlie", Age = 35 },

new Person { Name = "Diana", Age = 18 },

new Person { Name = "Edward", Age = 22 }

};

// Example 8: Combining Queries

var adultsSortedByName = people

.Where(p => p.Age >= 18)

.OrderBy(p => p.Name)

.Select(p => p.Name)

.ToList();

Console.WriteLine("\nAdults sorted by name:");

foreach (var name in adultsSortedByName)

{
Console.WriteLine(name);

Output:-

Adults sorted by name:

Alice

Bob

Charlie

Diana

Edward

You might also like