Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Mr. Shahid Jamil email id: shahid@biit.edu.

pk WhatsApp# 0315-5425199
Lecture 23-24

Note:

It is an intimation that following Lectures are not going to repeat and would
be part of mid-term & final exam as well.

(Week 11) Lecture 23-24

Objectives: Learning objectives of this lecture are

 Static Class and Extension Function


 GroupJoin Function - DataTable
 Inner Join Function - DataTable
 Left Outer Join Function - DataTable
 Create XML file
 XML Format Introduction
 Aggregation - XML
 Where Function - XML
 OrderBy, ThenBy Function - XML
 GroupBy Function - XML
 Inner Join Function – XML
 Assignment

Text Book & Resources: -Essential LINQ by Charlire Calvert


Online links:

Here is the YouTube link for the video explanation of the lecture:
https://youtu.be/zN09C3K08aQ

Here is the downloadable link for Complete Video (Google Drive):


https://drive.google.com/open?id=1DSZ3i3kxPlN7WLrInpV75HiAFZ5uunDQ

Here are links of same Video but in four (04) parts (Google Drive), in case of internet speed issue
https://drive.google.com/open?id=1t152fLONrll1U3DjPGjwMXaMeH5GSWew
https://drive.google.com/open?id=1QMTlJdKDVfdYE6BIrhvAKz9UkZ73cugL
https://drive.google.com/open?id=1lMaN4R_ipvgmHyk8giabQasVBG-tWUa-
https://drive.google.com/open?id=1kASBC90rIlgP_nWqzzpLDD1ga7aRI2cg

Here is link of Video for assignment explanation (Google Drive)


https://drive.google.com/open?id=1KiFjZZvIxQdAepp23wIxRYaZtbNunMY_

Here is downloadable link for complete Code (Google Drive)


https://drive.google.com/open?id=1eVQe8AbSZsSOuKrTvM9K-H2rpiPW9Jq_

1
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24

Static Class and Extension Method


Today we will deal with DataRows of DataTable and after query, we need to print them on screen. Today
we will use extension method to print the datarow object. For this we will first create a static class and
then we will define a static method. Here is the code sample for it:

public static class RataRowExtension


{
public static string Fields(this DataRow dr)
{
return
string.Format("{0},{1},{2},{3},{4},{5}",dr[0],dr[1],dr[2],dr[3],dr[4],dr[5]);
}
}

Similary static class and extension method for XElement class:

public static class XElementExtension


{
public static string Fields(this XElement et)
{
return string.Format("{0},{1},{2},{3},{4}", et.Element("Name").Value
, et.Element("Gender").Value
, et.Element("Dob").Value
, et.Element("Salary").Value
, et.Element("City").Value);
}
}

DataTable with DataRows


Today we are going to declare two datatable objects, one for departments and other for employees.
Here is the code sample for datatable objects, their columns and the dummy data(i.e. rows)

//Declare DataTable for Department


var dtDepartments = new DataTable();

//Define columns
var cId = new DataColumn("Id", Type.GetType("System.Int32"));
var cDepName = new DataColumn("DName", Type.GetType("System.String"));

//Add columns to Department Table


dtDepartments.Columns.Add(cId);
dtDepartments.Columns.Add(cDepName);

//Add records in Department Table


dtDepartments.Rows.Add(new object[] { 100, "Marketing" });
dtDepartments.Rows.Add(new object[] { 101, "HR" });
dtDepartments.Rows.Add(new object[] { 102, "Accounts" });
dtDepartments.Rows.Add(new object[] { 103, "QA" });

//////
//Declare Data
var dtEmployees = new DataTable();

2
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24
var cName = new DataColumn("Name", Type.GetType("System.String"));
var cGender = new DataColumn("Gender", Type.GetType("System.Char")); //e.g.
'F' or 'M'
var cDob = new DataColumn("Dob", Type.GetType("System.DateTime"));
var cSalary = new DataColumn("Salary", Type.GetType("System.Int32"));
var cCity = new DataColumn("City", Type.GetType("System.String"));
var cDeptId = new DataColumn("DeptId", Type.GetType("System.Int32"));

dtEmployees.Columns.Add(cName);
dtEmployees.Columns.Add(cGender);
dtEmployees.Columns.Add(cDob);
dtEmployees.Columns.Add(cSalary);
dtEmployees.Columns.Add(cCity);
dtEmployees.Columns.Add(cDeptId);

//add few records in employee table


dtEmployees.Rows.Add(new object[] { "Qasim", 'M', Convert.ToDateTime("25-Nov-
1998"), 45000,"Rawalpindi", 100 });
dtEmployees.Rows.Add(new object[] { "Fatima", 'F', Convert.ToDateTime("12-10-
1995"), 35000,"Lahore", 101 });
dtEmployees.Rows.Add(new object[] { "Nasir", 'M', Convert.ToDateTime("09-Jan-
1993"), 85000,"Rawalpindi", 101 });
dtEmployees.Rows.Add(new object[] { "Manzoor", 'M', Convert.ToDateTime("15-
Sep-1990"), 35000,"Islamabad", 102 });
dtEmployees.Rows.Add(new object[] { "Khalid", 'M', Convert.ToDateTime("01-02-
2001"), 25000,"Lahore", 101 });
dtEmployees.Rows.Add(new object[] { "Ayesha", 'F', Convert.ToDateTime("10-09-
1992"), 60000,"Rawalpindi", 101 });
dtEmployees.Rows.Add(new object[] { "Ahmed", 'M', Convert.ToDateTime("10-09-
1997"), 30000,"Islamabad", 102 });
dtEmployees.Rows.Add(new object[] { "Sana", 'F', Convert.ToDateTime("09-02-
2002"), 47000,"Rawalpindi", 100 });
dtEmployees.Rows.Add(new object[] { "Zulfiqar", 'M', Convert.ToDateTime("17-
06-1995"), 34000,"Islamabad", 102 });
dtEmployees.Rows.Add(new object[] { "Zaheer", 'M', Convert.ToDateTime("10-02-
1999"), 18000, "Lahore",0 });

GroupJoin Function – DataTable


GroupJoin is similar on DataTable as it was on Array and Collections. Following examples will explain the
concept:

//1.1 Group Join - DataTable


//GroupJoin is also know as Outer Join
Console.WriteLine("..............................");
Console.WriteLine("1.1 GroupJoin Function");
Console.WriteLine("..............................");

var query1 =
dtDepartments.AsEnumerable().GroupJoin(dtEmployees.AsEnumerable(),
dpt =>
dpt.Field<Int32>("Id"),
emp =>
emp.Field<Int32>("DeptId"),
(dpt,emps) => new

3
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24
{
DptName =
dpt.Field<String>("DName"),
Employees = emps//
IEnumerable<DataRow>
});
Console.WriteLine("Result of GroupJoin for Employees and Departments");
foreach (var g in query1)
{
Console.WriteLine("------------");
Console.WriteLine(g.DptName);
Console.WriteLine("-----------");
foreach (var emp in g.Employees)
{
Console.WriteLine(emp.Fields());
}

Inner Join Function – DataTable


Similary the Join which is also called Inner Join, here is the code sample:

//1.2 Inner Join Function - DataTable


//Inner Join simply called Join
Console.WriteLine("..............................");
Console.WriteLine("1.2 Inner Join Function");
Console.WriteLine("..............................");

var query2 = dtDepartments.AsEnumerable().Join(dtEmployees.AsEnumerable(),


d => d.Field<int>("Id"),
e => e.Field<int>("DeptId"),
(d, e) => new {

DeptName=d.Field<string>("DName"),
Employee = e// DataRow
});
//Inner Join of Department and Employee, commonly known as Join
Console.WriteLine("Inner Join of Department and Employee");
foreach (var g in query2)
{
Console.WriteLine("{0}::{1}",g.DeptName,g.Employee.Fields());
}

Left Outer Join Function – DataTable


Left Outer Join for datatable with the help of the example code:

//1.3 Left Outer Join Function - DataTable


Console.WriteLine("..............................");
Console.WriteLine("1.3 Left Outer Join Function");
Console.WriteLine("..............................");
var query3 =
dtEmployees.AsEnumerable().GroupJoin(dtDepartments.AsEnumerable(),
e =>
e.Field<int>("DeptId"),

4
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24
d => d.Field<int>("Id"),
(e, d) => new
{
Employee = e,
Depatments = d
})
.SelectMany(v =>
v.Depatments.DefaultIfEmpty(),
(a, b) => new
{
Name =
a.Employee.Field<string>("Name"),
Dob =
a.Employee.Field<DateTime>("Dob"),
Dept = b == null?
"...":b.Field<string>("DName")
});
foreach (var v in query3)
{
Console.WriteLine(v);
}

Creating XML files (with Data)


Firs you have to create following xml files with data as mentioned:

Employees.xml
<Employees>
<Employee>
<Name>Qasim</Name>
<Gender>M</Gender>
<Dob>25-Nov-1998</Dob>
<Salary>45000</Salary>
<City>Rawalpindi</City>
<DeptId>1</DeptId>
</Employee>

<Employee>
<Name>Fatima</Name>
<Gender>F</Gender>
<Dob>12-10-1995</Dob>
<Salary>35000</Salary>
<City>Lahore</City>
<DeptId>2</DeptId>
</Employee>

<Employee>
<Name>Nasir</Name>
<Gender>M</Gender>
<Dob>09-Jan-1993</Dob>
<Salary>85000</Salary>
<City>Lahore</City>
<DeptId>1</DeptId>
</Employee>

<Employee>
<Name>Manzoor</Name>

5
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24
<Gender>M</Gender>
<Dob>15-Sep-1990</Dob>
<Salary>35000</Salary>
<City>Islamabad</City>
<DeptId>3</DeptId>
</Employee>

<Employee>
<Name>Khalid</Name>
<Gender>M</Gender>
<Dob>01-02-2001</Dob>
<Salary>25000</Salary>
<City>Lahore</City>
<DeptId>1</DeptId>
</Employee>

<Employee>
<Name>Ayesha</Name>
<Gender>F</Gender>
<Dob>10-09-1992</Dob>
<Salary>60000</Salary>
<City>Rawalpindi</City>
<DeptId>2</DeptId>
</Employee>

<Employee>
<Name>Ahmed</Name>
<Gender>M</Gender>
<Dob>10-09-1997</Dob>
<Salary>30000</Salary>
<City>Rawalpindi</City>
<DeptId>1</DeptId>
</Employee>

<Employee>
<Name>Sana</Name>
<Gender>F</Gender>
<Dob>09-02-2002</Dob>
<Salary>47000</Salary>
<City>Rawalpindi</City>
<DeptId>3</DeptId>
</Employee>

<Employee>
<Name>Zulfiqar</Name>
<Gender>M</Gender>
<Dob>17-06-1995</Dob>
<Salary>34000</Salary>
<City>Islamabad</City>
<DeptId>2</DeptId>
</Employee>

<Employee>
<Name>Zaheer</Name>
<Gender>M</Gender>
<Dob>10-02-1999</Dob>
<Salary>18000</Salary>
<City>Lahore</City>

6
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24
<DeptId>3</DeptId>
</Employee>
</Employees>

Departments.xml
<Departments>
<Department Id="1">
<Name>HR</Name>
</Department>

<Department Id="2">
<Name>Marketing</Name>
</Department>

<Department Id="3">
<Name>Accounts</Name>
</Department>
</Departments>

Students.xml
<Students>
<Student Id="100" Gender="M">
<Name>Ali</Name>
<Discipline>BSCS</Discipline>
</Student>

<Student Id="101" Gender="F">


<Name>Ayesha</Name>
<Discipline>BSCS</Discipline>
</Student>

<Student Id="102" Gender="M">


<Name>Zahid</Name>
<Discipline>MCS</Discipline>
</Student>
</Students>

XML Format Introduction


XML file consists of user defined tags, and one root tag. As we can see in the above section.
Employee.xml file has root tag named ‘Employees’ and then this root tag has child tags named
‘Employee’ and then this tag has more child tags. In C# Sysm.XML.Ling namespace provides support for
xml file handling via Linq. XElement is a C# class which can hold one complete tag (i.e. Employees, or
Employee). So each tag of xml is XElement. More if we look at Students.xml file then we will see that
Employee tag has two attributes named ‘Id’ and ‘Gender’.

Here is XElement:

<Name>Zaheer</Name>

OR

<Employee>

7
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24
<Name>Zaheer</Name>
<Gender>M</Gender>
<Dob>10-02-1999</Dob>
<Salary>18000</Salary>
<City>Lahore</City>
<DeptId>3</DeptId>
</Employee>

Here are attributes of XElement:

<Student Id="101" Gender="F">

Here is the code stuff that how we will load xml document:

//First We will read XML file

var myFile = XElement.Load("Employees.xml");

var allEmployees = myFile.Elements("Employee");


var allDepartments = XElement.Load("Departments.xml").Elements("Department");
var allStudents = XElement.Load("Students.xml").Elements("Student");

Aggregation – XML
We can also apply aggregation on XML file. Here are examples of Count, Min, Max, Avg, and Sum

//3.1 Aggregations

var count = allEmployees.Count();


var maxSalary = allEmployees.Max(e => int.Parse(e.Element("Salary").Value));
var minSalary = allEmployees.Min(e => int.Parse(e.Element("Salary").Value));
var avgSalary = allEmployees.Average(e =>
int.Parse(e.Element("Salary").Value));
var sumSalary = allEmployees.Sum(e =>
Convert.ToInt32(e.Element("Salary").Value));
Console.WriteLine("---------------------");
Console.WriteLine("Aggregation on XML");
Console.WriteLine("---------------------");
Console.WriteLine("Count : {0}",count);
Console.WriteLine("Max Salary : {0}",maxSalary);
Console.WriteLine("Min Salary : {0}",minSalary);
Console.WriteLine("Avg Salary : {0}",avgSalary);
Console.WriteLine("Sum Salary : {0}",sumSalary);

Where Function – XML


In where we have covered Element as well as Attribute.

//3.2 LINQ Where on XML


Console.WriteLine("---------------------");
Console.WriteLine("Where on XML");
Console.WriteLine("---------------------");

8
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24
var query1 = allEmployees.Where(e => char.Parse(e.Element("Gender").Value) ==
'M');
Console.WriteLine("All Male Employees\n");
foreach (XElement emp in query1)
{
//Console.WriteLine(emp.Element("Name").Value);
Console.WriteLine(emp.Fields());
}

var query01 = allStudents.Where(e => char.Parse(e.Attribute("Gender").Value)


== 'M');
Console.WriteLine("All Male Students\n");
foreach (XElement std in query01)
{
Console.WriteLine("{0},{1},{2},{3}",std.Element("Name").Value
, std.Attribute("Id").Value
, std.Attribute("Gender").Value
, std.Element("Discipline").Value);
}

OrderBy, ThenBy Function – XML


//3.3 LINQ OrdeBy on XML
Console.WriteLine("---------------------");
Console.WriteLine("OrderBy on XML");
Console.WriteLine("---------------------");
var query2 = allEmployees.OrderBy(e => e.Element("Name").Value);
Console.WriteLine("Employees Sort By Name\n");
foreach (XElement emp in query2)
{
Console.WriteLine(emp.Fields());
}

Console.ReadKey();
Console.Clear();

var query3 = allEmployees.OrderByDescending(e =>


Convert.ToDateTime(e.Element("Dob").Value));
Console.WriteLine("\nEmployees Sort By Dob\n");
foreach (XElement emp in query3)
{
Console.WriteLine(emp.Fields());
}

Console.ReadKey();
Console.Clear();

var query4 = allEmployees.Where(e => char.Parse(e.Element("Gender").Value) ==


'M')
.OrderBy(e=>e.Element("City").Value);
Console.WriteLine("All Male Employees, Order by City\n");
foreach (XElement emp in query4)
{
Console.WriteLine(emp.Fields());
}
Console.ReadKey();
Console.Clear();

9
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24

var query5 = allEmployees.OrderBy(e => e.Element("City").Value)


.ThenByDescending(e =>
int.Parse(e.Element("Salary").Value));
Console.WriteLine("All Employees, Order by City. Then By Salary desc\n");
foreach (XElement emp in query5)
{
Console.WriteLine(emp.Fields());
}
Console.ReadKey();
Console.Clear();

GroupBy Function – XML


//3.4 GroupBy Function
Console.WriteLine("---------------------");
Console.WriteLine("GroupBy on XML");
Console.WriteLine("---------------------");
var query6 = allEmployees.GroupBy(e => e.Element("City").Value);
foreach (var g in query6)
{
Console.WriteLine("--------------");
Console.WriteLine("City Name:{0}, Total Employees:{1}",g.Key,g.Count());
Console.WriteLine("--------------");
foreach (var emp in g)
{
Console.WriteLine(emp.Fields());
}
}

Inner Join Function – XML


//3.5 Inner Join Function
Console.WriteLine("---------------------");
Console.WriteLine("Inner Join on XML");
Console.WriteLine("---------------------");
var query7 = allEmployees.Join(allDepartments,
e => e.Element("DeptId").Value,
d => d.Attribute("Id").Value,
(e, d) => new
{
EmpName = e.Element("Name").Value,
DeptName = d.Element("Name").Value,
Gender = e.Element("Gender").Value,
Dob = e.Element("Dob").Value
});
foreach (var detail in query7)
{
Console.WriteLine(detail);
}

10
Mr. Shahid Jamil email id: shahid@biit.edu.pk WhatsApp# 0315-5425199
Lecture 23-24

Assignment
Q1. In week-11 we applied two methods of Cross Join, Now you need to apply both methods
on two DataTables (i.e. dtEmployees and dtDepartments) and print the result.

Q2. For LINQ to XML you need to apply GroupJoin, Left Outer Join and Cross Join(Employees
and Departments).

Q3. Apply following queries for Employee and Dempartment XML


3.1 GroupBy on Department Name and print department name along with Highest
Salary Employee Details
3.2 Join Department,Employee and Print result

11

You might also like