System Programing
System Programing
System Programing
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.
LINQ to DataTable
Adding Columns to DataTable
Adding Rows to DataTable
Aggregate Functions
OrderBy Function
Where Function
Select Function
GroupBy Function
Assignment
Here is the YouTube link for the video explanation of the lecture:
https://youtu.be/VjdqNDorctg
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
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:
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.
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.
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);
We can add rows to datatable by two different ways. Following are both one by one.
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
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.
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.
//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]);
}
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);
}
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);
}
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());
}
8
Mr. Shahid Jamil email id: [email protected] WhatsApp# 0315-5425199
Lecture 21-22
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