Linq - part 3

 

https://github.com/vasanth32/Linq_Practice

E:\@udemy\Projects\Linq

https://www.javatpoint.com/linq

LINQ Join() Operators

In LINQ, Join() operators are used to join the two or more lists/collections and get the matched data from the collection based on the specified conditions. The behavior and functionality of Join() operators are the same as SQL joins.

In LINQ, We have different types of joins available. These are:

  1. INNER JOIN
  2. LEFT OUTER JOIN
  3. CROSS JOIN
  4. GROUP JOIN
OperatorDescription
Inner JoinIt returns the element from the collections which satisfy the specified expression.
Left Outer JoinIt returns all the elements from the left side collection and matching the elements with the right side collection.
Cross JoinIt returns the Cartesian product of elements in collections.
Group JoinThe join clause with an 'into' expression is called a group join


LINQ Inner Join

In LINQ, Inner join is used to return only the matched records or elements from the collections based on the specified conditions.

Syntax of LINQ Inner Join

Here is the syntax of using the LINQ Inner join to get the elements from the collections based on the specified condition.

  1. var result = from d in objDept  
  2. join e in objEmp  
  3. on d.DepId equals e.DeptId  
  4. select new  
  5. {  
  6. EmployeeName = e.Name,  
  7. DepartmentName = d.DepName  
  8. };  



  1.        List<Department> Dept = new List<Department>  
  2.     (){  
  3.     new Department{DepId=1,DepName="Software"},  
  4.     new Department{DepId=2,DepName="Finance"},  
  5.     new Department{DepId=3,DepName="Health"}  
  6.     };  
  7.     List<Employee>Emp = new List<Employee>  
  8.     ()  
  9.     {  
  10.     new Employee { EmpId=1,Name = "Akshay Tyagi", DeptId=1 },  
  11.     new Employee { EmpId=2,Name = "Vaishali Tyagi", DeptId=1 },  
  12.     new Employee { EmpId=3,Name = "Arpita Rai", DeptId=2 },  
  13.     new Employee { EmpId=4,Name = "Sateesh Alavala", DeptId =2},  
  14.     new Employee { EmpId=5,Name = "Madhav Sai"}  
  15.     };  
  16.     var result = from d in Dept  
  17.     join e in Emp  
  18.     on d.DepId equals e.DeptId  
  19.     select new  
  20.     {  
  21.     EmployeeName = e.Name,  
  22.     DepartmentName = d.DepName  
  23.     };  
  24.     foreach (var item in result)  
  25.     {  
  26.     Console.WriteLine(item.EmployeeName + "\t | " + item.DepartmentName);  
  27.     }  


LINQ Left Outer Join

In LINQ, LEFT JOIN or LEFT OUTER JOIN is used to return all the records or elements from the left side collection and matching the elements from the right side of the collection.

In LINQ, to achieve the LEFT Join behavior, it is mandatory to use the "INTO" keyword and "DefaultfEmpty()" method.

Syntax of LINQ Left Outer Join

The syntax of using the LINQ Left Outer Join to get all the elements from the collection and matching the element from the right collection.

  1. var result = from e in objEmp1  
  2. join d in objDept1  
  3. on e.DeptId equals d.DepId into empDept  
  4. from ed in empDept.DefaultIfEmpty()  
  5. select new  
  6. {  
  7.     EmployeeName = e.Name,  
  8.     DepartmentName = ed == null ? "No Department" : ed.DepName  
  9. }  


LINQ Cross Join

In LINQ, Cross join will produce the Cartesian product of the collections of items. There is no need for any condition to join the collection.

In LINQ Cross join, each element on the left side collection will be mapped to all the elements on the right side collection.

Syntax of LINQ Cross Join

Here is the syntax of using the LINQ Cross join to get the Cartesian product of the collection items.

  1. var result = from e in objEmp1  
  2. from d in objDept1  
  3. select new  
  4. {  
  5.     EmployeeName = e.Name,  
  6.     DepartmentName = d.DepName  
  7. };  


From the above syntax, each element in the "objEmp1" collection will be mapped to all the elements in the "objDept1" collection.


LINQ Group Join

In LINQ, a Join clause with an 'into' expression is called a Group join. In LINQ, Group join produces a sequence of the elements of the objects, which is based on the matching element from both left and right collections.

In case, if no matching element found from the right collection with the left collection, then the join clause will return an empty array. In LINQ, Group join is an equivalent to inner equi join except for the result of the elements organized into groups.

Syntax of LINQ Group Join

The syntax of using the LINQ Group Join to get the matching element from the given collections based on our requirement.

  1. var result = from d in objDept  
  2. join e in objEmp on d.DepId equals e.DeptId into empDept  
  3. select new  
  4. {  
  5.     DepartmentName = d.DepName,  
  6.     Employees = from emp2 in empDept  
  7.     orderby emp2.Name  
  8.      select emp2  
  9. };  

From the above syntax, we used a Join clause with an 'into' expression to get the matching elements from the collections.


LINQ Set Operations

In LINQ, Set Operators are used to return the set of the result based on the presence or absence of equivalent elements within the same or separate collections.

In LINQ, we have different types of set operators available. These are:

  1. UNION
  2. INTERSECT
  3. DISTINCT
  4. EXCEPT
OperatorsDescription
UNIONUnion operator combines multiple collections into single collection and return the resultant collection with unique element.
INTERSECTIt returns the element in a sequence, which is common in both the input sequence.
DISTINCTIt removes the duplicate elements from the collection and returns the collection with unique values.
EXCEPTIt returns the sequence element from the first input sequence, which is not present in the second input sequence.


LINQ Union Method

In LINQ, the Union method or operator is used to combine the multiple collections into a single collection and return the resultant collection with a unique element.



Syntax of LINQ union Method

Here is the syntax of using the union method to get the unique elements from the multiple collections.

  1. var result = count1.Union(count2);  

In the above syntax, we are combining two collections to get the result as a single collection using the union method.

  1.             string[] count1 = { "India""USA""UK""Australia" };  
  2.             string[] count2 = { "India""Canada""UK""China" };  
  3. //count1.Union(count2) is used to find out the unique element from both the collection  
  4.             var result = count1.Union(count2);  

LINQ Union() Method

LINQ Intersect Method

In LINQ, the Intersect method or operator is used to return the common elements from both the collections.

Here is the pictorial representation of the LINQ intersect method.

LINQ Intersect Method

LINQ Intersect method will combine both the collections into a single collection and return only the matching element from the collection.

Syntax of LINQ Intersect Method

The syntax of using the intersect method to get the matching elements from the multiple collections.

var result = count1.Intersect(count2); 

LINQ Intersect Method


LINQ Distinct Method

In LINQ, the Distinct method or operator is used to get only the distinct elements from the collection.

Here is the pictorial representation of the LINQ Distinct method.

LINQ Distinct Method

The LINQ Distinct method or operator is used to get only the distinct elements from the collection.

Syntax of LINQ Distinct Method

Here is the syntax of using distinct methods to get unique elements from the collection.

  1. IEnumerable<int> result = numbers.Distinct();  
  1.             string[] countries = { "UK""India""Australia""uk""india""USA" };  
  2. //apply the Distinct method to find out the different country names   
  3.             IEnumerable<string> result = countries.Distinct(StringComparer.OrdinalIgnoreCase);  

LINQ Distinct Method


LINQ SequenceEqual Method

In LINQ, the SequenceEqual method is used to compare the sequence of two collections that are equal or not. It determines two sequences whether they are equal or not by comparing the elements in a pair-wise manner, and two sequences contain the equality number of the element or not.

The LINQ SequenceEqual method will return the Boolean value true in case two sequence elements are equal, and all the elements match in both the sequences; otherwise, it will throw false.

Syntax of LINQ SequenceEqual Method

The syntax of using LINQ SequenceEqual method to check the given two collections are equal or not.

  1. var res1 = arr1.SequenceEqual(arr2);  

In the above syntax, we are using the LINQ SequenceEqual method to check whether "arr1" and "arr2" are equal or not.

        string[] array1 = { "welcome", "to", "tutlane", "com" };  

            string[] array2 = { "welcome", "TO", "Noida", "com" };  

            string[] array3 = { "welcome", "to", "noida" };  

            string[] array4 = { "WELCOME", "TO", "NOIDA" };  

//Sequence.Equal() method is used to check if both te sequences are equal or not  

            var res1 = array1.SequenceEqual(array2);  

            var res2 = array1.SequenceEqual(array2, StringComparer.OrdinalIgnoreCase);  

            var res3 = array1.SequenceEqual(array3);  

            var res4 = array3.SequenceEqual(array4, StringComparer.OrdinalIgnoreCase); 

 LINQ SequenceEqual() Method

LINQ Concat Method

In LINQ, the Concat method or operator is used to concatenate or append the two collection elements into a single collection, and it does not remove the duplicates from two sequences.

Here is the pictorial representation of the LINQ Concat Method.

LINQ Concat Method


  string[] array1 = { "a", "b", "c", "d" };  

  

            string[] array2 = { "c", "d", "e", "f" };  


            var result = array1.Concat(array2);  

LINQ Concat Method


LINQ Generation Operations

In LINQ, generation operations are used to create the new sequence of the elements. In LINQ, we have a different type of generation operator methods available. These are:

  1. DefaultfEmpty
  2. Range
  3. Repeat
  4. Empty

These LINQ generation operators will help us to generate a new sequence of elements.

The following table shows more detailed information related to generation operator methods.

MethodDescription
DefaultfEmptyIf the collection contains the empty elements, then it will return the default value.
EmptyIt returns the empty collection of sequences.
RangeIt returns the collection that contains a sequence of numbers.
RepeatIt returns a collection that contains the one repeated value-based on a specified length.

LINQ Range Method

In LINQ, the Range method or operator is used to generate the sequence of integer or numbers based on the specified values of the start index and end index.

Syntax of LINQ Range Method

Here is the syntax of the LINQ Range method to generate the sequence of numbers based on the specified index.

  1. IEnumerable<int> obj = Enumerable.Range(10010);  

From the above syntax, we defined the Range method with two parameters. Here, the first parameter shows the starting element of the integer, and the second integer is the one which tells us the limit up to which it can display the integer in a sequence.

LINQ Range Method

LINQ Repeat Method

In LINQ, the Repeat method or operator is used to generate the collection with the same number as the repeated times based on the specified index value.

Syntax of LINQ Repeat Method

Here is the syntax of the LINQ Repeat method to generate the repeated number based on specified index values.

  1. IEnumerable<int> obj = Enumerable.Repeat(10010);  

In the above syntax, we defined the Repeat method with two parameters. Here the first parameter tells the starting elements of the integer, and the second parameter is the one tells how many times the same number repeated in sequence.


LINQ Repeat() Method

LINQ Empty Method

In LINQ, the Empty method or operator is used to return the empty sequence of the collection.

Syntax of LINQ Empty Method

Here is the syntax of the LINQ Empty method to generate the collection with an empty sequence

LINQ to Objects

In LINQ, if we use "LINQ to Objects" in our applications, it will give us a chance to use IEnumerable or IEnumerable<T> collections directly in LINQ queries, without the use of any intermediate LINQ provider or API such as LINQ to SQL, or LINQ to XML. By using LINQ to Objects, we can apply the query to any of the Enumerable collections such as List<T>, Array or Dictionary <TKey, TValue>.

The LINQ to Objects provides a new way to get the data from the collections with LINQ Queries, but before that, there is a need to write a lot of foreach loops to get the data from the collections.

LINQ to Objects provides more advantages when compared with a traditional foreach loop. These are:

  1. They provide more readability when we use them with multiple conditions.
  2. It enables filtering, ordering, and grouping capabilities with minimal application code.
  3. They are portal to any data sources with less or no modifications.

If we use LINQ in complex operations, then we will see the benefits of using the LINQ, instead of traditional iteration loops.

  • LINQ to Strings
  • LINQ to String Array
  • LINQ to Int Array
  • LINQ to Files
  • LINQ to Lists

LINQ to Strings

LINQ to strings is nothing but writing the LINQ queries on String to get the required data from the string sequence. In LINQ, we can write queries on strings along with traditional string functions and regular expressions to perform the required operations on strings using the LINQ.

Syntax of LINQ to Strings

The syntax of writing the LINQ queries is:

  1. var result = from s in str.ToLowerInvariant().Split()  

In the above syntax, we have written the LINQ query on String to get the distinct element.


LINQ to String Array

LINQ to String Array means writing the LINQ queries on string array to get the required data. If we use LINQ queries on string arrays, we can get the required elements easily without writing the much code.

Syntax of LINQ to String Array

Here is the syntax of writing the LINQ queries on string Arrays to get the required element from array collection.

  1. IEnumerable<string> result = from a in arr  
  2.   
  3.                                          select a;  

In the above syntax, we have written the LINQ query to get the data from the "arr" string array.

Expression in LINQ

The lambda Expression can be assigned to the Func or Action type delegates to process over in-memory collections. The .NET compiler converts the lambda expression assigned to Func or Action type delegate into executable code at compile time.

LINQ introduced the new type called Expression that represents strongly typed lambda expression. It means lambda expression can also be assigned to Expression<TDelegate> type. The .NET compiler converts the lambda expression which is assigned to Expression<TDelegate> into an Expression tree instead of executable code. This expression tree is used by remote LINQ query providers as a data structure to build a runtime query out of it (such as LINQ-to-SQL, EntityFramework or any other LINQ query provider that implements IQueryable<T> interface).

The following figure illustrates differences when the lambda expression assigned to the Func or Action delegate and the Expression in LINQ.

ExpressionTree Process
Expression and Func

We will learn Expression tree in the next section but first, let's see how to define and invoke an Expression.

Define an 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:

Example: Define Func delegate for an expression in C#
public class Student 
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
}

Func<Student, bool> isTeenAger = s => s.Age > 12 && s.Age < 20;

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() {Name = "Steve", Age = 20 });

			Console.WriteLine(result);

Comments

Popular Posts