Naveen's Weblog

Bridge to future

Archive for the ‘LINQ To Objects’ Category

Basics of LINQ to objects with explanation and samples.

Multiple List Left Join in LINQ

Posted by codingsense on June 16, 2009

We had seen in earlier posts how to left join and right join 2 lists using LINQ. But what about multiple list joining is it in the same way or are there any challanges in the implementation.

Today we shall see how we can use left join on multiple list in a single query.

We will take a case of 3 classes Branch ( ID, Name) , Department(ID , Name, BranchID) and employees(ID,Name,DeptID)

Download Project – 2.9 Kb

If we would join the 3 similar tables in MSSQL then it would appear as

Select Emp.Name, Dept.Name, branch.Name from ((Employees as Emp left join 
Departments as Dept on Dept.ID = Emp.DeptID)left join 
Branches as branch on Dept.BranchID = branch.ID)

In the above query we can see that first we join Employees and department on Department ID and the output of that join is joined with branch on brachid. By following the same flow we can derive the same result using LINQ. The equivalent implementation in LINQ follows

var MultipleListJoin = from empdept in
                                   (from emp in ListOfEmployees
join dept in ListOfDepartment
on emp.DeptID equals dept.ID into JoinedEmpDept
from dept in JoinedEmpDept.DefaultIfEmpty()
select new                                    
{
EmployeeName = emp.Name,
BranchID = dept != null ? dept.BranchID : 0,
DepartmentName = dept != null ? dept.Name : null                                    
})
join branch in ListOfBranch on
                               empdept.BranchID equals branch.ID into JoinedwithBranch
from branch in JoinedwithBranch.DefaultIfEmpty()
select new                               
{
EmpName = empdept.EmployeeName,
DeptName = empdept.DepartmentName,
BranchName = branch != null ? branch.Name : string.Empty
};

In the above first we derive the intermediate ouput by joining Employee and Department

from emp in ListOfEmployees
join dept in ListOfDepartment
on emp.DeptID equals dept.ID into JoinedEmpDept
from dept in JoinedEmpDept.DefaultIfEmpty()
select new                                    
{
EmployeeName = emp.Name,
BranchID = dept != null ? dept.BranchID : 0,
DepartmentName = dept != null ? dept.Name : null}

and then use the intemediate output and join it with Branches to get the final result.

MultipleListLeftJoin

Hope you have got how to join multiple lists, for Right join follow the above implementataion in the reverse way.

Happy Learning :)

Posted in LINQ To Objects | Tagged: , , | 11 Comments »

Left Join, Right Join Using LINQ

Posted by codingsense on March 8, 2009

Hi Friends,

In this post let us see how we can handle Left Join and Right Join when using LINQ. There are no keywords defined in C#, we have to use DefaultIfEmpty() function to get the desired result.
Let us see how we can achieve it.

To make you understand better I use a Employee -> Department realation to explain.

First we shall create two classes namely Employee and Department

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

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

Lets create some objects of both the classes and fill some dummy data in it.

Employee emp1 = new Employee() { ID = 1, Name = "A", DeptID = 1};
Employee emp2 = new Employee() { ID = 2, Name = "B", DeptID = 1};
Employee emp3 = new Employee() { ID = 3, Name = "C", DeptID = 1 };
Employee emp4 = new Employee() { ID = 4, Name = "D", DeptID = 2 };
Employee emp5 = new Employee() { ID = 5, Name = "E", DeptID = 2 };
Employee emp6 = new Employee() { ID = 6, Name = "F", DeptID = 2 };
Employee emp7 = new Employee() { ID = 7, Name = "G", DeptID = 6 };
Employee emp8 = new Employee() { ID = 8, Name = "H", DeptID = 3 };
Employee emp9 = new Employee() { ID = 9, Name = "I", DeptID = 3 };
Employee emp10 = new Employee() { ID = 10, Name = "J", DeptID = 7};
Employee emp11 = new Employee() { ID = 11, Name = "K", DeptID = 7};
Employee emp12 = new Employee() { ID = 12, Name = "L", DeptID = 5};

Department Dept1 = new Department() { ID = 1, Name = "Development"};
Department Dept2 = new Department() { ID = 2, Name = "Testing"};
Department Dept3 = new Department() { ID = 3, Name = "Marketing"};
Department Dept4 = new Department() { ID = 4, Name = "Support"};

List<Employee> ListOfEmployees = new List<Employee>();
ListOfEmployees.AddRange((new Employee[] { emp1, emp2, emp3, emp4, emp5, emp6, emp7,
emp8, emp9, emp10, emp11, emp12 }));

List<Department> ListOfDepartment = new List<Department>();
ListOfDepartment.AddRange( new Department[]{ Dept1,Dept2,Dept3,Dept4});

So we finish loading the objects into ListOfEmployees and ListOfDepartments, using this lists we shall see how we can join them to get the results.
First let us see what would be the query in SQL if we had the same structure in our tables.
For Left join and right join we would have used the query

--Left Join in SQL
select Emp.Name, Dept.Name from Employee Emp left join Department Dept on
Emp.DeptID = Dept.ID

--Right Join In SQL
select Emp.Name, Dept.Name from Employee Emp right join Department Dept on
Emp.DeptID = Dept.ID

Using LINQ, Left Join can be acheived as follows

var LeftJoin = from emp in ListOfEmployees
join dept in ListOfDepartment
on emp.DeptID equals dept.ID into JoinedEmpDept 
from dept in JoinedEmpDept.DefaultIfEmpty()
select new                          
{
EmployeeName = emp.Name,
DepartmentName = dept != null ? dept.Name : null                          
};

And for Right Join there is no pretty difference, we just need to reverse the joining in first 2 lines. Here it follows

var RightJoin = from dept in ListOfDepartment
join employee in ListOfEmployees
on dept.ID equals employee.DeptID into joinDeptEmp
from employee in joinDeptEmp.DefaultIfEmpty()
select new                            
{
EmployeeName = employee != null ? employee.Name : null,
DepartmentName = dept.Name
};

Do you believe it will work ??? lets check it by displaying,

Console.WriteLine(string.Join("n" , LeftJoin.Select(emp => " Employee Name = " +
emp.EmployeeName + ", Department Name = " + emp.DepartmentName).ToArray<string>()));

Console.WriteLine(string.Join("n", RightJoin.Select(emp => " Employee Name = " +
emp.EmployeeName + ", Department Name = " + emp.DepartmentName).ToArray<string>()));

Output of Left Join in LINQ

Output of Left Join in LINQ

Output of Right Join in LINQ

Output of Right Join in LINQ

Great, it has worked. So friends in this way you can handle Left and Right Joins in LINQ, hope you understood the sample.

Next -> Multiple List Left Join

Happy Learning :)

Posted in LINQ To Objects | Tagged: , , | 24 Comments »

Join in LINQ

Posted by codingsense on March 8, 2009

Hi Friends,

In this post lets us try to understand how Join is handled using LINQ. We will take a sample that would make us clear what we are trying to acheive.

Consider a department that handles a type of category of items, it can be active or not. The class of the department will look like

public class Dept    
{
public int ID { get; set; }
public int CategoryID { get; set; }
public bool IsActive { get; set; }
} 

After creating the department class lets move to create the Items class

public class Item    
{
public int ID { get; set; }
public int DeptID { get; set; }
public int CategoryID { get; set; }
public bool IsActive { get; set; }
public int Quantity { get; set; }
}

First let us create a list of Department and Items

//Create Items            
Item itm1 = new Item() { ID = 1, DeptID = 1, CategoryID = 1, IsActive = true, Quantity = 30 };
Item itm2 = new Item() { ID = 2, DeptID = 1, CategoryID = 1, IsActive = false, Quantity = 5 };
Item itm3 = new Item() { ID = 3, DeptID = 1, CategoryID = 2, IsActive = true, Quantity = 2 };
Item itm4 = new Item() { ID = 4, DeptID = 1, CategoryID = 2, IsActive = false, Quantity = 0 };

Item itm5 = new Item() { ID = 5, DeptID = 2, CategoryID = 1, IsActive = true, Quantity = 0 };
Item itm6 = new Item() { ID = 6, DeptID = 2, CategoryID = 1, IsActive = false, Quantity = 0 };
Item itm7 = new Item() { ID = 7, DeptID = 2, CategoryID = 2, IsActive = true, Quantity = 20 };
Item itm8 = new Item() { ID = 8, DeptID = 2, CategoryID = 2, IsActive = false, Quantity = 5 };

Item[] ListOfItems = { itm1, itm2, itm3, itm4, itm5, itm6, itm7, itm8 };

//Create Departments            
Dept dept1 = new Dept() { ID = 1, CategoryID = 1, IsActive = true };
Dept dept2 = new Dept() { ID = 1, CategoryID = 1, IsActive = false};
Dept dept3 = new Dept() { ID = 1, CategoryID = 2, IsActive = true };
Dept dept4 = new Dept() { ID = 1, CategoryID = 2, IsActive = false };

Dept dept5 = new Dept() { ID = 2, CategoryID = 1, IsActive = true };
Dept dept6 = new Dept() { ID = 2, CategoryID = 1, IsActive = false };
Dept dept7 = new Dept() { ID = 2, CategoryID = 2, IsActive = true };
Dept dept8 = new Dept() { ID = 2, CategoryID = 2, IsActive = false };

Dept[] ListOfDept = { dept1, dept2, dept3, dept4,dept5,dept6,dept7,dept8 };

Lets move furthur to check how these two classes can be joined to derive the result

Join single column-> No of items in Department 1:
We will join the two classes on department id and get the the sum of items present in department 1.

//Single Join            
//List No of items in Dept 1            
int NoOfItems = (from dept in ListOfDept
join item in ListOfItems
on dept.ID equals item.DeptID 
where dept.ID == 1
select new { item.ID, item.Quantity }).Distinct().Sum(itm => itm.Quantity);

In the above code I am filtering the same records that are returned due to equijoin.

Join multiple columns -> Get the item * and dept * for the following criteria
Lets join the dept and item objects on the following criteria

Relation between Department and Items

Relation between Department and Items


and add a extra condition for Item.Quantity > 0 and retrive the values

First let us see how the above result are acheived without using join to make you clearly understand the difference between using and not using the join

var WithoutJoin = from dept in ListOfDept
from item in ListOfItems
where dept.ID == item.DeptID &&
dept.CategoryID == item.CategoryID &&
dept.IsActive == item.IsActive &&
item.IsActive == true &&
item.Quantity > 0
select new { item, dept };

Now lets retrive the same values using join

var WithJoin = from dept in ListOfDept
join item in ListOfItems
on new { deptid = dept.ID, catID = dept.CategoryID , isActive = dept.IsActive } equals 
new { deptid = item.DeptID, catID = item.CategoryID, isActive = item.IsActive }
where item.IsActive == true && item.Quantity > 0
select new { item, dept };

Hope you have understood how to join single column and join multiple columns using LINQ. If you need any clarification please feel free.

Happy Learning :)

Posted in LINQ To Objects | Tagged: , , | 1 Comment »

LINQ with best example – 2

Posted by codingsense on January 12, 2009

Hi friends,
In my previous post LINQ with best example – 1 , we had seen the basic concepts of linq with the company sample. Today we will move a bit furthur and see how LINQ can be used for an project handling Inventory.

 

The Inventory Sample

Downloads:
Download source code – 8 Kb

In inventory we will create 3 classes namely Customer, Item, and Sales. The Class diagram of the 3 classes are shown below.

classdiagram

Class Diagram

Create Customers, Items and Sales:
First let us insert some dummy records into the list of customer, Items and sales.

List<Customer> ListOfCustomer = new List<Customer>();
Customer C1 = new Customer() { Name = "Naveen", Area = "Mahalaxmi", City = "Bangalore", ID = 1 };
Customer C2 = new Customer() { Name = "Aatish", Area = "Layout", City = "Bangalore", ID = 2 };
Customer C3 = new Customer() { Name = "Manas", Area = "Layout", City = "Bangalore", ID = 3};
Customer C4 = new Customer() { Name = "Raghu", Area = "Mahalaxmi", City = "Bombay", ID = 4 };
ListOfCustomer.AddRange(new Customer[]{C1,C2,C3,C4});

List<Item> ListOfItems = new List<Item>();
Item I1 = new Item() { ID = 1, Name = "Monitor", Quantity = 15, UnitPrice = 5000 };
Item I2 = new Item() { ID = 2, Name = "Processor", Quantity = 10, UnitPrice = 10000};
Item I3 = new Item() { ID = 3, Name = "Keyboard", Quantity = 25 ,UnitPrice = 1000};
ListOfItems.AddRange(new Item[]{I1,I2,I3});

List<Sales> ListOfSales = new List<Sales>();
Sales S1 = new Sales() { CustomerID = 1, ItemID = 1, Quantity = 5 };
Sales S2 = new Sales() { CustomerID = 1, ItemID = 2, Quantity = 3 };
Sales S3 = new Sales() { CustomerID = 2, ItemID = 1, Quantity = 5 };
Sales S4 = new Sales() { CustomerID = 2, ItemID = 3, Quantity = 5 };
Sales S5 = new Sales() { CustomerID = 3, ItemID = 2, Quantity = 5 };
Sales S6 = new Sales() { CustomerID = 3, ItemID = 3, Quantity = 15};
ListOfSales.AddRange(new Sales[]{S1,S2,S3,S4,S5,S6});

Using the above classes we will query the following

  • List all customers
  • List customers from a specific city
  • No of customers in each city
  • No of items purchased by each customer
  • No of Items remaining in inventory
  • Amount received from each item
  • Amount paid by each customer

List all customers:
For listing the customers use the following code.

foreach (Customer c in ListOfCustomer)
{
Console.WriteLine(c.Name + "," + c.ID + "," + c.Area + "," + c.City);
}

List customers from a specific city:
For filltering the customer depending on a specific city you can use

var CustomerCity = from customer in ListOfCustomer
where customer.City == "Bangalore"                               
select new                               
{
Name = customer.Name,
ID = customer.ID
};

You can also use where customer.City.StartsWith(“Ba”) to filter a customer when there is an entry in Quick search box.

No of customers in each city:
For finding the No. of customers from each city we have to group the customers on key ‘CITY’.

var CustomersInCity = from customer in ListOfCustomer
group customer by customer.City into GroupedCustomer
select new                               
{
City = GroupedCustomer.Key,
EmployeeCount = GroupedCustomer.Count()
};

No of items purchased by each customer:
For searching the items purchased by each customer we shall join all 3 lists and derive the output.

var CustomerItem = from cust in ListOfCustomer
join sale in ListOfSales 
on cust.ID equals sale.CustomerID 
join item in ListOfItems
on sale.ItemID equals item.ID 
select new { CustName = cust.Name, ItmName = item.Name, Qnt = sale.Quantity };

No of Items remaining in inventory:
For finding the remaining items in inventory we shall group the items in sales with itemid key. After which, we get quantity of each item sold. Then we will join the output of ItemID and SoldItems with Items in which we will get the No of items purchased. Subtracting Initial Count with Sold Count we get the items in Inventory.

var RemainingInventory = from itm in ListOfItems
join sold in
                                      (
from sale in ListOfSales
group sale by sale.ItemID into GroupedItemInSale
select new                                          
{
ID = GroupedItemInSale.Key,
Qty = GroupedItemInSale.Sum(sold => sold.Quantity)
})
on itm.ID equals sold.ID
select new { itm.Name, RemQnt = itm.Quantity - sold.Qty };

Amount received from each item:
For getting the amount received from each item, first we require the total no of each item sold, so we shall group the sales on ItemId. By this we get the ItemID and no of items sold. Then the unit Pice of each item can be multiplied by the no of peices sold by joining the first query output with Item List.

var IncomeFromSales = from item in ListOfItems
join sold in
                                      (
from sale in ListOfSales
group sale by sale.ItemID into GroupedItems
select new                                          
{
ID = GroupedItems.Key,
Quantity = GroupedItems.Sum(GI => GI.Quantity)
})
on item.ID equals sold.ID 
select new { Name = item.Name, AmountRec = item.UnitPrice * sold.Quantity };

Amount paid by each customer:
For this first let us analyze what is required and then split it till we go to the solution
1) Customer Name with Total Amount – the final output we require is Customer Name and Total Amount
2) ListOfcustomer, (Customer ID, each item quantity , each item price) – Customer Name can be fetched by joining LIstofcustomer with an output that has (customerID, Quantity of each item purchased and item price for each)
3) ListOfCustomer, Joining(Item and Sales) – to attain the output for (2) can be attained if we join Item and sales.

So now reverse the process and the following query will be acheived.

var AmountPaidByCustomers = from cust in ListOfCustomer
join GroupedAmount in
(from GroupAmount in
(from itm in ListOfItems
join sale in ListOfSales
on itm.ID equals sale.ItemID
select new                                              
{
sale.CustomerID,
Amount = sale.Quantity * itm.UnitPrice
})
group GroupAmount by GroupAmount.CustomerID into GroupedAmount
select new                                      
{CustomerID = GroupedAmount.Key,
Amount = GroupedAmount.Sum(i => i.Amount)
})
on cust.ID equals GroupedAmount.CustomerID
select new                              
{cust.Name,GroupedAmount.Amount};

The above analysis helped in identifying how to proceed, So the steps followed to attain the final output
1) Join Sales and Item -> Get CustomerID, Amount = ItemID * Unit Pice ( this will be the amount for each type of item purchased)
2) Group the output of (1) on CustomerID -> Gets CustomerID, Amount ( this will be the total amount Purchased by the customer)
3) Join result of (2) with LIstOfCustomer on ID -> Gets Customer Name and Amount

Output :

Final Output

Final Output

 

 

By the last problem we come to know that problem are simple to solve, but you should analyze the problems and split it up in simple steps.
Hope you have understood the Inventory sample, if you have any doubts or want a different sample then you can post a comment.

 

Happy Learning :)

Posted in LINQ To Objects | Tagged: , , | 2 Comments »

Search word or phrase within a file using LINQ

Posted by codingsense on September 16, 2008

Hi found a nice way to search a word or phrase within a file, so thought of sharing with you all.

string DirPath = Application.StartupPath + "\Search\";
string SearchText = "Temp";
string[] Files = (from file in new DirectoryInfo(DirPath).GetFiles()
                     where new StreamReader(file.FullName).ReadToEnd().Contains(SearchText)
                     select file.Name).ToArray<string>();


Download Sample – 21 kb

If you know a better way, please post a comment.

Happy Learning :)

Posted in LINQ To Objects | Tagged: , , | 3 Comments »

Difference between Select and SelectMany in LINQ

Posted by codingsense on September 16, 2008

The difference between select and selectMany can be seen when we are accessing data from multilevel classes.

Download Sample Code – 2.62 Kb

In the below example we shall see what exactly is the difference while accessing the properties.

When we access some data by using select it gives us the data that is grouped under the parent (i.e gives multiple arrays). To access the output we need to loop twice.

////This code shows how to use Select()             
var Query2 = Builders.Select(Build => Build.Locations);

// Notice that two foreach loops are required to iterate through
// the results because the query returns a collection of arrays.            
foreach (List<String> BuildList in Query2)
{
        foreach (string builds in BuildList)
        {
                Console.WriteLine(builds);
        }

        Console.WriteLine();
}

But using the same sample when we use select many it gives the selected items in one array(i.e it give the output as it is joining all the output from select command)

// Query using SelectMany().            
var query1 = Builders.SelectMany(Build => Build.Locations);

// Only one foreach loop is required to iterate through the
// results because it is a one-dimensional collection.
// Select many joins the output of all the sub collections in to one.            
foreach (string Loc in query1)
        Console.WriteLine(Loc);

Output:

Difference select and selectMany

Difference Select and SelectMany

Happy learning :)

Posted in LINQ To Objects | Tagged: , , | 11 Comments »

LINQ to system files and processes

Posted by codingsense on September 16, 2008


I was just thinking where and all linq can be used, surpirsingly i found that whatever i thought to do i was able to implement linq to make it much better.

Firstly i thought how linq can be used with file system and check what i got.

LINQ to System Files:

Here i made a sample which will search the files from system directory and list the files that are of .dll extension and have size greater than 100000 bytes

string DirPath = System.Environment.GetFolderPath(Environment.SpecialFolder.System);
string[] Files = (from file in new DirectoryInfo(DirPath).GetFiles()
                     where file.Extension == ".dll" && file.Length > 1000000
                     select file.Name).ToArray<string>();


Next i thought how linq can be used with processes

LINQ to system Processes:

Here we shall see how a running process can be handled using LINQ. This sample will list all the processes that are currently running and order them in ascending order of the memory taken

var ProcInfo = from proc in Process.GetProcesses()
       orderby proc.PagedMemorySize64
       select new { Name = proc.ProcessName , Memory = proc.PagedMemorySize64};


Download sample – 24 kb

So people just keep thinking where all you can utilize linq and you will get more creatives ways to use it.

 

Happy learing :)

Posted in LINQ To Objects | Tagged: , | Leave a Comment »

Samples for all Linq functions at one place

Posted by codingsense on September 11, 2008

I had many confusions when i used linq for the first time. For each function i searched its usage and then used it. It was pretty time consuming. So i decided to make a sample that will explain almost all linq functions at one place.

Here comes the sample.
Download sample – 45.2Kb

int[] arrNumbers1 = { 1, 4, 8, 4, 15, 12, 15};
int[] arrNumbers2 = { 2, 9, 3, 5, 8, 18, 15 };

//********Aggregate**********
//The LINQ aggregate operators allow you to perform simple math
//operations over the elements in a collection in a sequence

//1.Take min of the elements in a collection
int ArrgrNum = arrNumbers2.Aggregate((s, t) => Math.Min(s, t));

//2.Lets reverse a string
string sentence = "I went with her for a walk in evening";
// Split the string into individual words.
string[] words = sentence.Split(' ');
// Join each word to the beginning of the new sentence to reverse the word oder.
string reverse = words.Aggregate((CurrentWord, next) => next + " " + CurrentWord);
Console.WriteLine(reverse);

//3.Lets check with an example to find the factorial of a given Number.
int N = 5;
IEnumerable intSequence = Enumerable.Range(1, N);
int agg = intSequence.Aggregate((av, e) => av * e);
Console.WriteLine("{0}! = {1}", N, agg);

//*********ALL*****************
//All<> does not return a list of the items in the collection.
//It returns a bool indicating if all the items in the list match an expression.

//We will first check whether all NO's in the array are even or not
var AllEven = arrNumbers1.All(temp => temp % 2 == 0);

//Here we check all the numbers in the array are greater than 1 or not
var AllGreater = arrNumbers2.All(Greater => Greater > 1);

//********Any*****************
//Any is reverse of All, it checks like "If any element satisfies the condition return true"
var AnyEven = arrNumbers1.Any(temp => temp % 2 == 0);

//******Average*********
var AvgNum =  arrNumbers1.Average();

//conditional avereage
//This takes the average of all elemets in an array whose value are greater than 8
//If less then it will replace it with 8 and take the average
var AvgOther = arrNumbers1.Average(temp => temp > 8 ? temp : 8);

//********Cast***********
var strArray =  arrNumbers1.Cast();

//********Concat********
//Concatenates both the array
var ConcatArr = arrNumbers2.Concat(arrNumbers1);

//*********Contains******
bool hasElement = arrNumbers1.Contains(2);

//*********Distinct*********
//Removes the duplicates and returns only distinct elements
int[] DistinctOnly = arrNumbers1.Distinct().ToArray();

//*********ELement at********
//Returns Element at give index
var ElementAt = arrNumbers2.ElementAt(3);

//ElementAtOrDefault
//returns the element if its present at the given index
//Or returns its default eg: int 0, stirng empty
var ElementAtOrDef = arrNumbers2.ElementAtOrDefault(15);

//*********Except eg***********
//Selects the elements other than the specified in parameter
var ExceptEg = arrNumbers2.Except(arrNumbers1);
var ExceptEg1 = arrNumbers1.Except(Enumerable.Range(1,5));

//*********First*********
//Returns the first element that matches the condition
var FirstEle = arrNumbers1.First(temp => temp > 8);

//********FirstOrDefault******
//Returns the first element that matches the condition or
//returns the default value
var FirstOrDef = arrNumbers1.FirstOrDefault(temp => temp > 15);

//******GetValue*********
//Gets value of the element at given Index
var GetValuesAtIndex = arrNumbers1.GetValue(3);

//*********Intersect**********
//Returns the elements those are comman in both the arrays
var IntersectOfBoth = arrNumbers1.Intersect(arrNumbers2);

//********Last***********
//Gives the last element matching the condition specified in the parameter
var Last = arrNumbers2.Last(temp => temp > 6);

//*********LastOrdefault********
//Gives the last element matching the condition specified in the parameter
//If not found then returns the default value
var LastOrDef = arrNumbers2.LastOrDefault(temp => temp > 150);

//***********MAX**********
//Returns the max element in the collection
var MaxEle = arrNumbers2.Max();

//**********MIN***********
//Returns the min element in the collection
var MinEle = arrNumbers2.Min();

//********OrderBy**********
//Orders the list in ascending order
var OrderBY = arrNumbers2.OrderBy(x => x);

//****OrderByDescending******
//ORders the list in Descendig order
var DscArray = arrNumbers2.OrderByDescending(x => x);

//********Reverse**********
//Reverses the list
var ReverseArr = arrNumbers2.Reverse();

//********Select***********
//Selects the element that satisfies the given condition
//here we will select all elements as power of 2
var SelectArr = arrNumbers2.Select(ele => Math.Pow(2,ele));

//*********SequenceEqual******
//If both the arrays are equal return true else return false
bool AreEqual = arrNumbers2.SequenceEqual(arrNumbers1);

//********Set Value**********
//Sets the given value to the element in the collection at given index
arrNumbers1.SetValue(100, 2);

//**********Single*************
//Returns the index of the element whose value is equal to the given parameter
//If it has 0 or 2 elements with same value then it gives an error.
int SingleIndex = arrNumbers1.Single(imp => imp == 1);

//*********SingleDefault**********
//Returns the index of the element whose value is equal to the given parameter
//If no element with the given value then it returns the default
int SingleDef = arrNumbers1.SingleOrDefault(imp => imp == 10);

//**********Skip*********
//Skip first 3 elements and returs other elements
var SkipFirstElements = arrNumbers2.Skip(3);

//*********SkipWhile********
//Here in this sample we will extract only those no that are
//divisible by 3
var SkipConditional = arrNumbers1.SkipWhile(num => num % 3 != 0);

//********Sum***********
//Get the sum of an array
var SumOfArray = arrNumbers1.Sum();

//*********Take*********
//Its just the reverse operation of skip
//here it takes the first n elements specified in the parameter
var Take = arrNumbers2.Take(3);

//*********TakeWhile*********
//Takes only those elements that are not divisible by 3
var TakeWhile = arrNumbers2.TakeWhile(num => num % 3 != 0);

//*********ToArray***********
//converts the IEnumerable ouput an array of type specified in T
int[] IntArray = arrNumbers1.Take(3).ToArray();

//********Union***********
//Union of both the arrays - only unique
int[] UnionOfBoth = arrNumbers1.Union(arrNumbers2).ToArray();

//**********Where***********
//Select elements those are greater than 5
int[] GreaterThan5 = arrNumbers2.Where(x => x > 5).ToArray();

Any suggestions are wide open.

Happy learning :)

Posted in LINQ To Objects | Tagged: , | 3 Comments »

LINQ with best example – 1

Posted by codingsense on September 8, 2008

What is LINQ??

LINQ stand for Language-Integrated Query is now available as a integral part of Visual Studio 2008.

LINQ has a great power of querying on any source of data, data source could be the collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and that are give below.

  • LINQ to Object
  • LINQ to ADO.Net
    • LINQ to SQL
    • LINQ to Dataset
    • LINQ to Entities
  • LINQ to XML 

Basics samples of LINQ:

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

 

Assuming you know the basics of LINQ I will continue with a bit high end sample lets move further with an example of a company.

 

The Company Sample

Downloads:

Download complete Project (56.66kb)

Here we will see how a linq can be utilized in a company module. The company class will contain a Collection of employee class and employee will contain a struct for individual addresses.

 Hierarchy:

CompanyHierarchyLinq

Company Hierarchy

If we have a project with above hierarchy, let’s see how we can use LINQ to access details from multilevel classes. After creation of companies we will try to find the details at multilevel and see how conditionally data can be fetched.
1)  List details of employees
2)  Count no of employees in each company
3)  List employees who are staying in Bangalore
4)  List employee who is paid highest in each companies
5)  Overall Highest paid employee
6)  Salary paid by companies in each city
7)  Salary paid by each company in each city.

List details of employees:
Now we shall list all the employees with their details and company name.

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

Here we use sub queries since we need all employee details with their respective company name and both the details are at different levels. So first we Loops through the companies in the company list from comp in ListCompany and then within each selected company it loops through each employee from emp in comp.ListEmp Count no of employees in each company:

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

List employees who are staying in Bangalore: Here we use compound from clause to retrieve the employees who are staying in any city that contains BAN or ban.

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 };

List employee who is paid highest in each companies: For finding the highest paid employee we first loop through all the companies and employees in each company using compound from clause. Where condition filters only those employees those have the salary equal to the max salary in current company.

Var EmpHighSal = 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 }; 

Overall Highest paid employee: The same above procedure is followed but the only difference comes in the where condition where we match the employee's salary to the max salary from all the companies.

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 };

Salary paid by companies in each city: Here we will group by city and sum up all the salaries of the employees who are staying in that city.

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)};

 
Salary paid by each company in each city. Here for each company a group by clause is applied and from each company employees staying at different locations are fetched.

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) })};

 
Next >> LINQ with best example - 2

More references on LINQ: Standard Query Operators in a Nutshell: http://msdn.microsoft.com/en-us/library/bb308959.aspx#linqoverview_topic8 More LINQ: http://msdn.microsoft.com/en-us/library/bb397676.aspx

Suggestions are most welcome. 
Happy learning :)

Posted in LINQ To Objects | Tagged: , , | 2 Comments »

 
Follow

Get every new post delivered to your Inbox.