Pages

Search

Thursday, February 23, 2012

Linq and Extenstions Example

Linq helps to perform logical calculations with in memory by loading the object(s) at run time.
Just as like how we write sql queries in database to fetch the final list or table as required the similar can be achieved using linq. This also helps to reduce the lines of code (loc) to perform the calculations or logical relation of objects. For logically relation of objects before linq, developer has to create objects may be in a loop and add to collection etc…
Where as in case of linq, the same can be achieved with less number of locs. Also performing the logical relations or calculations with objects or arrays, etc.. using Linq are quite fater and gives better performance.

Regarding Extensions, .NET Framework has given an option for the developer to add extra methods to the framework. This methodology helps to improve the reusability across applications by just adding the extension reference. The methods that are added using extensions can be added to the class which is within the framework or can be added to the user defined class.
Ex:-
In my app I have a functionality to check if the given string in the UI is numeric, may be the same is required in other interfaces of my application.
“System.String” class has several methods, but has not method like “IsNumber()”.
So I will create an extension for “System.String” adding “IsNumber()” method.
I will put in the logic required and within my application across the modules I can just say like
txtName.Text.IsNumber() which returns Boolean to validate.


Below example illustrates an example to find the total salary paid to an employee between the given financial years.

Random objRand = null;

private void button1_Click(object sender, EventArgs e)

{

try

{

//collection for list of employees

List emps = new List();

//collection for list of salary for each employee

//yearly basis from 2011 to 2040

List empsals = new List();



objRand = new Random();

//Looping for 100 employees

for (int i = 1; i <= 100; i++)

{

//creating an employee object and adding to collection

//generating a random employee name of 10 characters in length

//random string is generated using extensions

emps.Add(new Employee() { ID = i, Name = objRand.NextString(10) });

for (int j = 2011; j < 2040; j++)

//creating sal object for each employee and for each year between 2011 and 2014

//sal is also random

empsals.Add(new EmployeeSal() { ID = i, Year = j, Sal = objRand.Next(10000, 50000) });

}

//trying to get the total salary paid to each employee between 2011 to 2040

var obj = (from emp1 in

(from emp in emps //inner join between employee and employee sal

from empsal in empsals

where

emp.ID == empsal.ID //join condition

select new { emp.Name, empsal.Sal }) //selecting the emp name and sal (one to many)

group emp1 by emp1.Name //grouping based on emp name

).ToDictionary(

l => l.Key, n => n.Sum((ss) => ss.Sal) //getting the emp name and
summing up the total sal paid
);
//obj is a dictionary, with key as employee name and value as total salary

}

catch (Exception exp)

{

MessageBox.Show("Error : " + exp.Message);

}

}

}


//random string extension method

public static class RandomExtensions

{

public static string NextString(this Random argRandom, int length)

{

//generating a random string of given lenght whose characters

//ascii code falls between 0 to 255

StringBuilder objString = new StringBuilder();

for (int l = 0; l < length; l++)

objString.Append((char)argRandom.Next(0, 255));

return objString.ToString();

}

}



//Employee and Employee Sal classes

public class Employee

{

public string Name;

public int ID;

}

public class EmployeeSal

{

public int ID;

public int Year;

public float Sal;

}

No comments:

Post a Comment