May 14, 2014

Linq OuterJoin

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

namespace JoinUsingLinq
{
    class Program
    {
        public static DBHmanDataContext db = new DBHmanDataContext();
        static void Main(string[] args)
        {
            //OuterJoin();
            //LeftOuterJoin();
            //RightOuterJoin();
            //Contact();
            Console.ReadLine();
        }

        static void OuterJoin()
        {
            var sql = from depart in db.Departments
                      join emp in db.Employees
                      on depart.DepartmentId equals emp.DepartmentId
                      select new
                      {
                          Department=depart.DepartmentName,
                          FullName=emp.FirstName + " " + emp.LastName,
                          Age=emp.Age
                      };
            foreach (var item in sql)
            {
                Console.WriteLine(item + "\t");
            }
        }

        static void LeftOuterJoin()
        {
            var sql = from depart in db.Departments
                      join emp in db.Employees
                      on depart.DepartmentId equals emp.DepartmentId into temp
                      from t in temp.DefaultIfEmpty()
                      select new
                      {
                          Department = depart.DepartmentName,
                          FullName = t.FirstName + " " + t.LastName,
                          Age = t.Age
                      };

            foreach (var item in sql)
            {
                Console.WriteLine(item + "\t");
            }
        }

        static void RightOuterJoin()
        {
            var sql = from emp in db.Employees
                      join depart in db.Departments
                      on emp.DepartmentId equals depart.DepartmentId into temp
                      from t in temp.DefaultIfEmpty()
                      select new
                      {
                          Department = t.DepartmentName,
                          FullName = emp.FirstName + " " + emp.LastName,
                          Age = emp.Age
                      };

            foreach (var item in sql)
            {
                Console.WriteLine(item + "\t");
            }
        }

        static void Contact()
        {
            var sql1 = from depart in db.Departments select depart.DepartmentName;
            var sql2 = from emp in db.Employees select emp.LastName;
            var contactquery = sql1.Concat(sql2);
            foreach (var item in contactquery)
            {
                Console.WriteLine(item + "\t");
            }
        }
    }
}

0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib