Tuesday, August 19, 2008

Better Linq with better example - 1

Here in this example we take an example of 2 companies with many employees and learn how to fetch data from multilevel list (list within list) or multilevel classes( class within a class) using LINQ.

In the following example i have tried to cover all the things that can be explained using a company example.

Just copy and paste the following console application.



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

namespace ITCompany
{
class Program
{
static void Main(string[] args)
{
//Create a list of Employees
List LEmp1 = new List();
LEmp1.Add(new Employee() { Name = "Emp01", Age = 24, salary = 40000, Address = new Address() { PinCode = 123451, City = "Bangalore" }});
LEmp1.Add(new Employee() { Name = "Emp02", Age = 25, salary = 35000, Address = new Address() { PinCode = 123452, City = "Delhi" } });
LEmp1.Add(new Employee() { Name = "Emp03", Age = 24, salary = 22000, Address = new Address() { PinCode = 123453, City = "Bombay" } });
LEmp1.Add(new Employee() { Name = "Emp04", Age = 25, salary = 14000, Address = new Address() { PinCode = 123454, City = "Chennai" } });
LEmp1.Add(new Employee() { Name = "Emp05", Age = 26, salary = 25000, Address = new Address() { PinCode = 123455, City = "Bangalore" } });

Company cmp1 = new Company() { Name = "Relyon", ListEmp = LEmp1};

List LEmp2 = new List();
LEmp2.Add(new Employee() { Name = "Emp07", Age = 25, salary = 35000, Address = new Address() { PinCode = 123456, City = "Bangalore" } });
LEmp2.Add(new Employee() { Name = "Emp08", Age = 24, salary = 15000, Address = new Address() { PinCode = 123457, City = "Bombay" } });
LEmp2.Add(new Employee() { Name = "Emp09", Age = 25, salary = 10000, Address = new Address() { PinCode = 123458, City = "Delhi" } });
LEmp2.Add(new Employee() { Name = "Emp10", Age = 26, salary = 25000, Address = new Address() { PinCode = 123459, City = "Bangalore" } });

Company cmp2 = new Company() { Name = "CellOn" , ListEmp = LEmp2};

Company[] ListCompany = { cmp1, cmp2 };

//
//Employee Details
//
Console.WriteLine("--------------------------------------------------------------------");
Console.WriteLine("Employee Details");
Console.WriteLine("--------------------------------------------------------------------");
Console.WriteLine("Company | Name | Age | Salary | Address |");
Console.WriteLine("--------------------------------------------------------------------");

var EmpDetails = from comp in ListCompany
select new
{
Emp = (from emp in comp.ListEmp
select new { Company = comp.Name, emp })
};

foreach (var t in EmpDetails)
{
Console.WriteLine(string.Join("\n", t.Emp.Select(emp => emp.Company + " |" + emp.emp.Name + " |" + emp.emp.Age + " |" + emp.emp.salary + " |" + emp.emp.Address.City + "-" + emp.emp.Address.PinCode).ToArray()));
}

Console.WriteLine();
Console.WriteLine();

//
//company with Employee count
//
Console.WriteLine("--------------------------------------------------");
Console.WriteLine("Nos of employees");
Console.WriteLine("--------------------------------------------------");

var LessEmp = from Comp in ListCompany
select new
{
Comp.Name,
EmpCount = Comp.ListEmp.Count
};

foreach(var t in LessEmp)
{
Console.WriteLine("Company Name : " + t.Name + ", Nos Of Employees : " + t.EmpCount);
}
Console.WriteLine(); Console.WriteLine();

//
//Employees who are staying in BANGALORE
//
Console.WriteLine("--------------------------------------------------");
Console.WriteLine("Employees statying in bangalore");
Console.WriteLine("--------------------------------------------------");

var EmpInACity = from comp in ListCompany
from emplist in comp.ListEmp
where emplist.Address.City.ToUpper().Contains("BAN")
select new { CompName = comp.Name, EmployeeName = emplist.Name };

foreach (var t in EmpInACity)
{
Console.WriteLine("Company Name : " + t.CompName + ", Employee Name : " + t.EmployeeName);
}
Console.WriteLine(); Console.WriteLine();

//
//Employee with Hightest salary in each company
//
Console.WriteLine("--------------------------------------------------");
Console.WriteLine("Highest paid employee in each company");
Console.WriteLine("--------------------------------------------------");

var EmpHighSalEachComp = from comp in ListCompany
from empHigh in comp.ListEmp
where empHigh.salary == comp.ListEmp.Max(HighEmp => HighEmp.salary)
select new { CompanyName = comp.Name, EmpHighName = empHigh.Name, EmpHighSal = empHigh.salary};

foreach (var t in EmpHighSalEachComp)
{
Console.WriteLine("Company : " + t.CompanyName + ", Employee : " + t.EmpHighName + ", Salary : " + t.EmpHighSal);
}
Console.WriteLine(); Console.WriteLine();

//
//Employee with Hightest salary
//
Console.WriteLine("--------------------------------------------------");
Console.WriteLine("Highest paid employee from all companies");
Console.WriteLine("--------------------------------------------------");

var EmpHighSal = from comp in ListCompany
from emp in comp.ListEmp
where emp.salary == ListCompany.Max(TComp => TComp.ListEmp.Max(HighEmp => HighEmp.salary))
select new { CompanyName = comp.Name , EmployeeName = emp.Name, EmpSal = emp.salary};

foreach (var t in EmpHighSal)
{
Console.WriteLine("Company : " + t.CompanyName + ", Employee : " + t.EmployeeName + ", Salary : " + t.EmpSal);
}
Console.WriteLine(); Console.WriteLine();

//
//Salary Paid in Each City together by all companies
//
Console.WriteLine("--------------------------------------------------");
Console.WriteLine("Payment done in cities together by all companies");
Console.WriteLine("--------------------------------------------------");

var CompanyCityWise = from comp in ListCompany
from emp in comp.ListEmp
group emp by emp.Address.City into CityWiseEmp
select new { State = CityWiseEmp.Key, TotalSalary = CityWiseEmp.Sum(emp => emp.salary) };

foreach (var t in CompanyCityWise)
{
Console.WriteLine("City : " + t.State + ", " + "Total Salary : " + t.TotalSalary);
}
Console.WriteLine(); Console.WriteLine();

//
//Salary Paid in Each City by each company
//
Console.WriteLine("--------------------------------------------------");
Console.WriteLine("Payment done in cities by each company");
Console.WriteLine("--------------------------------------------------");

var CityWiseSalary = from comp in ListCompany
select new
{
comp.Name,
Emp =(
from emp in comp.ListEmp
group emp by emp.Address.City into CityWiseEmp
select new { State = CityWiseEmp.Key, TotalSalary = CityWiseEmp.Sum(emp => emp.salary) })
};

foreach (var t in CityWiseSalary)
{
//t.emp comes as a structure so to easy the printing
//we will use string.join to join all the values in a single string
//It can also be done by looping through t.emp and
//printing t.emp.state and t.emp.totalsalary separately

Console.WriteLine("company : " + t.Name + "\n" + string.Join("\n", t.Emp.Select(emp => emp.State + " : " + emp.TotalSalary).ToArray()));
Console.WriteLine(); Console.WriteLine();
}
Console.WriteLine(); Console.WriteLine();


Console.Read();
}
}

public class Company
{
public string Name
{ get; set; }

public List ListEmp
{ get; set; }
}

public class Employee
{
public string Name
{ get; set; }

public Address Address
{ get; set; }

public int Age
{ get; set; }

public double salary
{ get; set; }
}

public struct Address
{
public int PinCode
{ get; set; }
public string City
{ get; set; }
}
}


Output of the above program:



If any suggestions for improving the access or improving the class are always open.

If you need example on any specific topic you can leave a comment and it will be included in the coming posts.

Keep Learning. :)

Sunday, August 17, 2008

Exploring LINQ Functions - Select, Min, Max, Average, ToArray()

Here is a sample program which will help you to learn some basic functions of LINQ.
The example is of a company in which there are some employees. We will try to explore some functions that are related to this example.

We will
1) list all the employees
2) Find Max salaried employee
3) Find Min Salaried Employee
4) Average salary paid by the company




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

namespace SampleLINQ
{
class Program
{
static void Main(string[] args)
{
//Create a list of Employees
List LEmp = new List();
LEmp.Add(new Employee() { Name = "Emp1", Age = 24, salary = 40000 });
LEmp.Add(new Employee() { Name = "Emp2", Age = 25, salary = 35000 });
LEmp.Add(new Employee() { Name = "Emp3", Age = 24, salary = 20000 });
LEmp.Add(new Employee() { Name = "Emp4", Age = 25, salary = 20000 });
LEmp.Add(new Employee() { Name = "Emp5", Age = 26, salary = 25000 });

//Names of employees
Console.WriteLine("List Of employees");
Console.WriteLine(string.Join("\n", LEmp.Select(emp => emp.Name).ToArray()));
Console.WriteLine();

//Average salary paid
Console.WriteLine("Average Salary Paid");
Console.WriteLine(LEmp.Average(emp => emp.salary));
Console.WriteLine();

//Find employees with Max Salary and print
Employee[] MaxSalary = (from mSal in LEmp
where mSal.salary == LEmp.Max(emp => emp.salary)
select mSal).ToArray();

Console.WriteLine("Highest salaried Employees");
Console.WriteLine(string.Join(",", MaxSalary.Select(emp => emp.Name).ToArray()));
Console.WriteLine();

//Find employees with Min Salary and print
Employee[] MinSalary = (from mSal in LEmp
where mSal.salary == LEmp.Min(emp => emp.salary)
select mSal).ToArray();

Console.WriteLine("Least salaried Employees");
Console.WriteLine(string.Join(",", MinSalary.Select(emp => emp.Name).ToArray()));
Console.WriteLine();

//Show the console
Console.Read();

//The following line can also be used to fetch the names of highest or least salaried employee
//All the above operations are done in a single line.
//Console.WriteLine(string.Join(",", LCust.Where(cust => cust.salary == LCust.Max(emp => emp.salary)).Select(cust => cust.Name).ToArray()));

}
}

public class Employee
{
public string Name
{get;set;}

public int Age
{get;set;}

public double salary
{get;set;}
}
}

Wednesday, May 7, 2008

Object and Collection Initializers

This is an interesting feature that will seem more valuable once you go through the below example.

Imagine a class Employee which has the properties like Name and ID

To add two employees and to list them required the following code till c# 2.0.




using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee("Naveen",1);
Employee emp2 = new Employee("Jonny", 2);

Console.WriteLine("Employee List :");
Console.WriteLine("----------------");
Console.WriteLine("ID Name");
Console.WriteLine("----------------");
Console.WriteLine("{0} {1}", emp1.ID, emp1.Name);
Console.WriteLine("{0} {1}", emp2.ID, emp2.Name);
Console.Read();
}

public class Employee
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}

private int id;
public int ID
{
get { return id; }
set { id = value; }
}

public Employee(string Name, int ID)
{
this.Name = Name;
this.ID = ID;
}
}
}
}



Now watch on whats new in c# 3.0. Life is simplified with the the Object Initailizers.





using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Employee emp1 = new Employee() { Name = "Naveen", ID = 1 };
Employee emp2 = new Employee() { Name = "Jonny" };

Console.WriteLine("Employee List :");
Console.WriteLine("----------------");
Console.WriteLine("ID Name");
Console.WriteLine("----------------");
Console.WriteLine("{0} {1}", emp1.ID, emp1.Name);
Console.WriteLine("{0} {1}", emp2.ID, emp2.Name);
Console.Read();
}

public class Employee
{
public string Name { get; set; }
public int ID{get;set;}
}
}
}


The improvements
1. if check the employee class you will find it much simpler, with no much code.
The constructor is removed, as well as the private variables are missing.
Still the code is running smoothly with data.
When the C# "Orcas" compiler encounters an empty get/set property implementation
like above, it will now automatically generate a private field for you within your
class, and implement a public getter and setter property implementation to it.

2. When creating a instance of the Employee class we can see some new things.
Here comes the concept of object Initializers. while creating the instance itself
we can specify which property is to be set with what value. This helps to avoid
creating overloads for the constructor.

Hope you have enjoyed the example. Try some more and explore the concepts.
Catch you soon with some other stuffs.
:-)

Friday, May 2, 2008

Extension methods with C# 3.5

Here is an example of Extension methods using C# 3.5

In this example we will put our own function in Frameworks string data type.

This will help user to print the the content of the stirng to console.





using System;
namespace ConsoleApplication1
{
public static class ExtendString
{
public static void PrintToConsole(this string str)
{
Console.WriteLine(str);
}
}
class Program
{
static void Main(string[] args)
{
string s = "Naveen.Prabhu";
s.PrintToConsole();
Console.Read();
}
}
}


Hope this will help you to understand the use of extension methods.

Create your own samples and take maximum use of this feature. :-)

Whats new in C# 3.5 compared with C# 2.0

The key features that are intorduced in C# 3.5 are


We will explore them in coming posts.. Till then let me find some simpler Samples to make you understand concepts better.. :-)

Thursday, May 1, 2008

Basic sample of LINQ

Here is an sample which helps in understanding LINQ better..

In this sample we will list the items in the inventory and search for the items that are finished.



using System;
using System.Linq;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Products[] ProductsList = {
new Products(){ Name = "Laptop", RemainingCount = 1},
new Products(){ Name = "CD", RemainingCount = 0},
new Products{ Name = "DVD", RemainingCount = 0},
new Products{ Name = "Cabinet", RemainingCount = 2}
};

Console.WriteLine("Total Inventory Items ::");

var Inventory = from Product in ProductsList
orderby Product.Name
select new { Name = Product.Name, RemCount = Product.RemainingCount };

foreach (var Item in Inventory)
Console.WriteLine(" Inventory has {0} peice of {1}", Item.RemCount, Item.Name );

Console.WriteLine();
Console.WriteLine();

Console.WriteLine("Empty Inventory Items ::");

var EmptyInventory = from Product in ProductsList
orderby Product.Name
where Product.RemainingCount == 0
select new { Product.Name};

foreach (var Item in EmptyInventory)
Console.WriteLine(" {0}", Item.Name);

Console.Read();
}

class Products
{
public string Name{get; set;}
public int RemainingCount{get; set;}
}
}
}



Hope you got the example executed..

For More LINQ Functions click here

Keep Learning