System Programing

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

Mr. Shahid Jamil email id: [email protected].

pk WhatsApp# 0315-5425199
Lecture 21-22

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 21-22

Objectives: Learning objectives of this lecture are

 LINQ to DataTable
 Adding Columns to DataTable
 Adding Rows to DataTable
 Aggregate Functions
 OrderBy Function
 Where Function
 Select Function
 GroupBy Function
 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/VjdqNDorctg

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


https://drive.google.com/open?id=11-pCEkxKtohf0ddtkcHSFKH0WuxJbPVO

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=11uYXzDLbC5S6daG5WvCj_rKyFl5Mu97h
https://drive.google.com/open?id=1D-9h1L2OAUEmmxHjRIum2ebrFaqWQeyn
https://drive.google.com/open?id=1J1_hgS7dKwTo2piNXL0tmlevFKsrzAQ1
https://drive.google.com/open?id=1N2lSSLi89DIJ4CshnQd0RMZbR8BmTQA0

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


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

Here is downloadable link for complete Code (Google Drive)


https://drive.google.com/open?id=1YmzYYKPCfPpvtmeghBF-xVgE-vrKSVuv

1
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22

LINQ to DataTable
DataTable is data type which is hold by C# inside System.Data namespace. A DataTable object
represents tabular data as an in-memory, tabular cache of rows, columns, and constraints. You typically
use the DataTable class to perform any disconnected data access. The DataTable is a central object in
the ADO.NET library. Other objects that use the DataTable include the DataSet and the DataView.

For creating a DataTable you first create an instance of the DataTable class, and then add DataColumn
objects that define the type of data to be held and insert DataRow objects that contain the data. The
following code demonstrates the creation of a data table:

//Create the DataTable named "Order"

DataTable order = new DataTable ("Order");

Using this code you are creating an empty data table for which the TableName property is set to Order.
You can use this property to access this data table from a DataTableCollection.

Adding Columns to DataTable


A DataTable contains a collection of DataColumn objects referenced by the Columns property of the
table. This collection of columns, along with any constraints, defines the schema, or structure, of the
table. The DataTable object is not useful until it has a schema, which is created by adding DataColumn
objects and setting the constraints of each column. Constraints help maintain data integrity by limiting
the data that can be placed in the column.

You can set up an auto-increment column, by setting the AutoIncrement property of your data column
to true. After that, you set AutoIncrementSeed to the value of the first number you want and set
AutoIncrementStep to the value you want to increment each time a new row is added.

Here we study that how we can add columns to DataTable along with their datatypes.

var dtEmployee = new DataTable();

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 cDepartment = new DataColumn("Department",
Type.GetType("System.String"));

dtEmployee.Columns.Add(cName);
dtEmployee.Columns.Add(cGender);
dtEmployee.Columns.Add(cDob);

2
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22
dtEmployee.Columns.Add(cSalary);
dtEmployee.Columns.Add(cDepartment);

Adding Rows to DataTable


After the DataTable object is created and contains DataColumn objects, you can populate the DataTable
object by adding DataRow objects. Use the DataRow object and it's properties and methods to retrieve
and evaluate; and insert, delete, and update the values in the DataTable. The DataRowCollection
represents the actual DataRow objects in the DataTable. DataRowCollection has an Add method that
accepts a DataRow object. The Add method is also overloaded to accept an array of objects instead of a
DataRow object.

We can add rows to datatable by two different ways. Following are both one by one.

//add few records to the table


//Method-1 to add record
dtEmployee.Rows.Add(new object[] {"Qasim",'M',Convert.ToDateTime("25-Nov-
1998"),45000,"Marketing"});
//Method-2 to add record
var record = dtEmployee.NewRow();
record["Name"] = "Fatima";
record["Gender"] = 'F';
record["Dob"] = Convert.ToDateTime("12-10-1995");
record["Salary"] = 35000;
record["Department"] = "HR";
dtEmployee.Rows.Add(record);

dtEmployee.Rows.Add(new object[] { "Nasir", 'M', Convert.ToDateTime("09-Jan-


1993"), 85000, "HR" });
dtEmployee.Rows.Add(new object[] { "Manzoor", 'M', Convert.ToDateTime("15-
Sep-1990"), 35000, "Accounts" });
dtEmployee.Rows.Add(new object[] { "Khalid", 'M', Convert.ToDateTime("01-02-
2001"), 25000, "HR" });
dtEmployee.Rows.Add(new object[] { "Ayesha", 'F', Convert.ToDateTime("10-09-
1992"), 60000, "HR" });
dtEmployee.Rows.Add(new object[] { "Ahmed", 'M', Convert.ToDateTime("10-09-
1997"), 30000, "Accounts" });
dtEmployee.Rows.Add(new object[] { "Sana", 'F', Convert.ToDateTime("09-02-
2002"), 47000, "Marketing" });
dtEmployee.Rows.Add(new object[] { "Zulfiqar", 'M', Convert.ToDateTime("17-
06-1995"), 34000, "Accounts" });

You can delete a DataRow from the DataRowCollection by calling the Remove method of the
DataRowCollection, or by calling the Delete method of the DataRow object. The Remove method
removes the row from the collection. In contrast, Delete marks the DataRow for removal. The actual
removal occurs when you call AcceptChanges method. The DataRow object doesn't have an Undelete
method. However, in some situations, you can use the RejectChanges method to roll back to a previous
state when the deleted row was still there. Be aware that executing the RejectChanges method copies
the Original data row version to the Current data row version.

3
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22

Query DataTable using LINQ


LINQ is an excellent way for querying different data sources using C#.With LINQ queries we can query
different data sources such as XML.Instead of using different querying languages such as XPath or SQL
,we can use C# regardless of the type of data source.

When using LINQ we need to be aware of just the LINQ query operators such as Select,Where.

LINQ queries can only be used with data sources which implements the IEnumerable <T> interface.This
is a requirement for the data source to be queried using the linq queries.Most of the collections in .NET
implements this interface ,so we can query most of the collections using linq.

Since ado.net datatable doesn’t implement this interface hence we can not use linq queries for querying
the datatable directly.

If we try to access linq extension methods on the datatable directly ,we will see that there are no
extension methods available for the datatable.

To query datatable using linq we call the AsEnumerable() method of the DataTable.Calling this method
on the DataTable returns an object which implements the IEnumerable<T> interface.Now we can
perform LINQ queries on this object.

To use this method we need to do the following

Add a reference to the System.Data.DataSetExtensions.This is usually added by default.

Add the namespace System.Linq

4
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22

After adding the above namespace if we call the AsEnumerable() method on the datatable ,we are able
to access LINQ extension methods on the datatable

LINQ can help to perform complex queries on a datatable easily.We can use the different querying
capabilities of the linq for performing different operations.For example we can project only few specific
columns from a datatable using the select operation

Aggregate Functions
LINQ is very helpful for calculating Count, Max, Min, Avg, and Sum of records in datatable. Using LINQ it
is very easy to calculate these functions. The following examples will depicts that how easy it is to
calculate aggregate functions using LINQ.

//Apply Aggregate Functions


//Query-1 Count
var eCount = dtEmployee.AsEnumerable().Count();
Console.WriteLine("Count of Employees: {0}",eCount);

//Query-2 Sum
var salarySum = dtEmployee.AsEnumerable().Sum(e => e.Field<Int32>("Salary"));
Console.WriteLine("Sum of Salary of all Employees: {0}", salarySum);

//Query-3 Average
var salaryAvg =
dtEmployee.AsEnumerable().Average(e=>e.Field<Int32>("Salary"));
Console.WriteLine("Avg of Salary of all Employees: {0}", salaryAvg);

//Query-4 Max
var youngestEmp = dtEmployee.AsEnumerable().Max(e=>e.Field<DateTime>("Dob"));
Console.WriteLine("Dob of youngest Employee: {0}", youngestEmp.ToString("dd-
MMM-yyyy"));

//Query-5 Min
var eldestEmp = dtEmployee.AsEnumerable().Min(e => e.Field<DateTime>("Dob"));

5
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22
Console.WriteLine("Dob of Eldest Employee: {0}", eldestEmp.ToString("dd-MMM-
yyyy"));

OrderBy Function
OrderBy sorts the values of a collection in ascending or descending order. It sorts the collection in
ascending order by default because ascending keyword is optional here. Use descending keyword to sort
collection in descending order. OrderByDescending sorts the collection in descending order.

Similarly we can use OrderBy of linq on datatable to perform data to shown in desired sequence.

/////
///Apply OrderBy
///
//Query-6 OrderBy Name
Console.WriteLine("Employees OrderBy Name");
var query6 = dtEmployee.AsEnumerable().OrderBy(e => e.Field<String>("Name"));
foreach (var emp in query6)
{
Console.WriteLine("{0},{1},{2},{3},{4}", emp["Name"], emp["Gender"],
emp[2], emp[3], emp[4]);
}

//Query-7 OrderByDescending Salary


Console.WriteLine("Employees OrderByDescending Salary");
var query7 = dtEmployee.AsEnumerable().OrderByDescending(e =>
e.Field<Int32>("Salary"));
foreach (var emp in query7)
{
Console.WriteLine("{0},{1},{2},{3},{4}", emp[0], emp[1], emp[2], emp[3],
emp[4]);
}

//Query-8 OrderBy Department, ThenBy Salary


Console.WriteLine("Employees OrderBy Department,Salary");
var query8 =
dtEmployee.AsEnumerable().OrderBy(e=>e.Field<String>("Department")).ThenBy(e =>
e.Field<Int32>("Salary"));
foreach (var emp in query8)
{
Console.WriteLine("{0},{1},{2},{3},{4}", emp[0], emp[1], emp[2], emp[3],
emp[4]);
}

//Query-9 OrderBy Gender, ThenBy Dob desc


Console.WriteLine("Employees OrderBy Gender,Dob desc");
var query9 = dtEmployee.AsEnumerable()
.OrderBy(e => e.Field<Char>("Gender"))
.ThenByDescending(e => e.Field<DateTime>("dOB"));
foreach (var emp in query9)
{
Console.WriteLine("{0},{1},{2},{3},{4}", emp[0], emp[1], emp[2], emp[3],
emp[4]);
}

6
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22

Where Function
The extension method Where() is defined in the Enumerable class. If you check the signature of the
Where extension method, you will find the Where method accepts a predicate delegate as
Func<Student, bool>. This means you can pass any delegate function that accepts a Student object as an
input parameter and returns a Boolean value as shown in the below figure. The lambda expression
works as a delegate passed in the Where clause.

//Apply Where
//Query-10 Where Salary between 30000 and 50000
Console.WriteLine("Between Salary 30000-50000");
var query10 = dtEmployee.AsEnumerable().Where(e => e.Field<int>("Salary") >=
30000 && e.Field<int>("Salary") <= 50000);
foreach (var emp in query10)
{
Console.WriteLine("{0},{1},{2},{3},{4}", emp[0], emp[1], emp[2], emp[3],
emp[4]);
}

Select Function
There are two projection operators available in LINQ. 1) Select 2) SelectMany. The Select operator
always returns an IEnumerable collection, which contains elements based on a transformation function.
It is similar to the Select clause of SQL that produces a flat result set. The select operator can be used to
formulate the result as per our requirement. It can be used to return a collection of custom class or
anonymous type, which includes properties as per our need.

//Apply Select
//Query-11 Name of all Employees
Console.WriteLine("Select only Name for all Employees");
var query11 = dtEmployee.AsEnumerable().Select(e => e.Field<String>("Name"))
.OrderBy(v=>v);
foreach (var nm in query11)
{
Console.WriteLine(nm);
}
//Query-12 Name and Salary of all Employees
Console.WriteLine("Select Name, Salary for all Employees");
var query12 = dtEmployee.AsEnumerable()
.Select(e => new {
Name=e.Field<String>("Name"),
Salary=e.Field<int>("Salary")
});
foreach (var v in query12)
{
Console.WriteLine(v);
}

//Query-12_1 Name and Salary of all Employees


Console.WriteLine("Select Name, Salary for all Employees");
var query12_1 = dtEmployee.AsEnumerable()
.Select(e => new
{
Name = e.Field<String>("Name"),
Salary = e.Field<int>("Salary")

7
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22
})
.OrderBy(v=>v.Name);
foreach (var v in query12_1)
{
Console.WriteLine(v);
}

//Query-13 Name and Salary of all Employees order by Salary


Console.WriteLine("Select Name, Salary,Dob for all Employees OrderBy
Salary");
var query13 = dtEmployee.AsEnumerable().Select(e => new {
Name =
e.Field<String>("Name"),
Salary =
e.Field<int>("Salary"),
Dob =
e.Field<DateTime>("Dob").ToShortDateString()//.ToString("dd-MMMM-yyyy")
})
.OrderBy(v=>v.Salary);
foreach (var v in query13)
{
Console.WriteLine(v);
}

GroupBy Function
The grouping operators do the same thing as the GroupBy clause of SQL query. The grouping operators
create a group of elements based on the given key. This group is contained in a special type of collection
that implements an IGrouping<TKey,TSource> interface where TKey is a key value, on which the group
has been formed and TSource is the collection of elements that matches with the grouping key value.

The GroupBy operator returns a group of elements from the given collection based on some key value.
Each group is represented by IGrouping<TKey, TElement> object. Also, the GroupBy method has eight
overload methods, so you can use appropriate extension method based on your requirement in method
syntax.

//Group By
//Query-14 Group By Department
Console.WriteLine("Group by Department having Count Method-I");
var query14 = dtEmployee.AsEnumerable().GroupBy(e =>
e.Field<string>("Department"));
foreach (var g in query14)
{
Console.WriteLine("{0},{1}",g.Key,g.Count());
}

//Query-15 Group By Department


Console.WriteLine("Group by Department having Max Salary Method-I");
var query15 = dtEmployee.AsEnumerable().GroupBy(e =>
e.Field<string>("Department"));
foreach (var g in query15)
{
Console.WriteLine("{0},{1}", g.Key, g.Max(e=>e.Field<int>("Salary")));
}

8
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22

//Query-15_1 Group By Department


Console.WriteLine("Group by Department having Max Salary Method-I");
var query15_1 = dtEmployee.AsEnumerable().GroupBy(e =>
e.Field<string>("Department"))
.OrderBy(v=>v.Key);
foreach (var g in query15_1)
{
Console.WriteLine("{0},{1}", g.Key, g.Max(e => e.Field<int>("Salary")));
}

//Query-16 Group By Department Same as of 14


Console.WriteLine("Group by Department having Count Method-II");
var query16 = dtEmployee.AsEnumerable().GroupBy(e =>
e.Field<string>("Department"))
.Select(g => new
{g.Key,Count=g.Count() });
foreach (var v in query16)
{
Console.WriteLine("{0},{1}", v.Key, v.Count);
}

//Query-17 Group By Department Same as of 15


Console.WriteLine("Group by Department having Max Salary Method-II");
var query17 = dtEmployee.AsEnumerable().GroupBy(e =>
e.Field<string>("Department"))
.Select(g => new {
g.Key,
MaxSalary = g.Max(e =>
e.Field<int>("Salary"))
});
foreach (var v in query17)
{
Console.WriteLine("{0},{1}", v.Key,v.MaxSalary);
}
//Query-18 Group By Department Print All Employees
Console.WriteLine("Group by Department having Employees");
var query18 = dtEmployee.AsEnumerable().GroupBy(e =>
e.Field<string>("Department"));

foreach (var g in query18)


{
Console.WriteLine("-----------------");
Console.WriteLine("{0}", g.Key);
Console.WriteLine("-----------------");
foreach (var emp in g)
{
Console.WriteLine("{0},{1},{2},{3},{4}", emp[0], emp[1], emp[2],
emp[3], emp[4]);
}
}

//Query-19 Group By Gender Print All Employees


Console.WriteLine("Group by Gender having Employees");
var query19 = dtEmployee.AsEnumerable().GroupBy(e =>
e.Field<char>("Gender"));

foreach (var g in query19)

9
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22
{
Console.WriteLine("-----------------");
Console.WriteLine("{0}", g.Key);
Console.WriteLine("-----------------");
foreach (var emp in g)
{
Console.WriteLine("{0},{1},{2},{3},{4}", emp[0], emp[1], emp[2],
emp[3], emp[4]);
}
}

Assignment
Q1. Create DataTable of Type Student with following Columns Name as String, CGPA as
float, Discipline as String.Then add 10 dummy rows in the datatable.

Q2. Apply GroupBy Function to Q1. datatable and print the students on the basis of
Discipline (i.e. GroupBy Discipline) Same output as of Query-18

Q3. Print Highest CGPA Student from Each Discipline Hint[User GroupBy, OrderBy, First
of LINQ]

10

You might also like