Joins in Linq

   
  
            var getTeams = from e in Employees.ListEmployee()
                           join x in Team.TeamMembers()
                           on e.EmpTeamId equals x.TeamId
                           select new
                           {
                               EmployeeName = e.EmployeeName,
                               TeamName = x.TeamName,
                               TeamID = x.TeamId
                           };
 

In this example, students and grades are two collections. The inner join is performed using the join clause in the LINQ query, where the StudentId property from the Grade class is matched with the Id property from the Student class.


  

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

class Program
{
    static void Main()
    {
        // Sample data
        List students = new List
        {
            new Student { Id = 1, Name = "John" },
            new Student { Id = 2, Name = "Alice" },
            new Student { Id = 3, Name = "Bob" }
        };

        List grades = new List
        {
            new Grade { StudentId = 1, Course = "Math", Score = 90 },
            new Grade { StudentId = 2, Course = "English", Score = 85 },
            new Grade { StudentId = 3, Course = "Math", Score = 88 }
        };

        // Inner join using LINQ
        var query = from student in students
                    join grade in grades on student.Id equals grade.StudentId
                    select new
                    {
                        student.Name,
                        grade.Course,
                        grade.Score
                    };

        // Displaying the result
        foreach (var result in query)
        {
            Console.WriteLine($"Student: {result.Name}, Course: {result.Course}, Score: {result.Score}");
        }
    }
}

// Sample classes representing the data structure
class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Grade
{
    public int StudentId { get; set; }
    public string Course { get; set; }
    public int Score { get; set; }
}

Left Join In Linq
  

    

    
    
    
      var orderForBooks = from bk in Book.GetBook()
                      join ordr in Order.GetOrder()
                      on bk.BookID equals ordr.BookID
                      into a
                      from b in a.DefaultIfEmpty(new Order())
                      select new
                      {
                          x=bk.BookID,
                          Name = bk.BookNm, 
                          y=b.PaymentMode
                      }; 

  foreach (var item in orderForBooks)
  {
      Console.WriteLine(item);
  } 
  
  
  

Comments