Naveen's Weblog

Bridge to future

Posts Tagged ‘LINQ’

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 🙂

Advertisements

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 »

LINQ To SQL – Employee Sample

Posted by codingsense on December 16, 2008

Introduction:

In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language.
 

Employee Sample of LINQ to SQL


Download Code (With Database) – 414 Kb

 

First let me explain you how to create a project for using LINQ to SQL

  • Creating the project:
  • In VS 2008 editor go to FIle -> New -> Project -> Windows Application. Set the target framework to 3.5

  • Attach database file:
  • Attach database file by right clicking on project in project explorer -> Add -> Existing Item -> locate the database file and click ok

  • Create LINQ to SQL Class:
  • Right click on project in project explorer -> Add -> New Item -> Select LINQ to SQL Classes and click add

  • Link Tables to Data Context
  • Double click on attached database , it will get open in server explorer, double click on the .dbml file (LINQ to SQL file) in project explorer, then drag the tables or any item from the server explorer and drop it on the opened .dbml file. The datacontext will link the tables to your program.

By the above steps you will be able to work with LINQ to SQL.

Now let me brief on the sample project of employee.

First i created a windows application project with Target framework 3.5 and named it as LinqToSQl.

linqtosqlcreateproject

Create Project

Then added a new item of Linq to sql class and named it as Employee, after the creation the IDE will automatically create a Data Access layer with name EmployeeDataContext.

linqtosqladdnewlinqtosql

New .dbml File

Then i attached an employee database with name Employee.mdf.
Open the Employee.dbml file

linqtosqlemployeedbmlblankscreen

.dbml file

Drag the database objects that you will use and drop on the Opened dbml file. I added 1 Employee table and 2 stored procedures named USP_Employee_Delete and USP_Employee_InsertOrUpdate. The tables will be placed in the left hand side and other functions views and stored procedures will be palced in the method pane on the right hand side.

linqtosqldragstoredprocedures

Drag SQL Objects

In this project I have done 3 things Search an employe, Insert or Update an employee and delete an employee using DataGridView and LINQ to SQL combination.

Search an employee:

linqtosqlselectemployee

Search Employee

For searching a particular employee we can use

string SearchString = textBox1.Text;

EmployeeDataContext edc = new EmployeeDataContext();

var FilteredEmployees = from employee in edc.Employees
 where employee.FirstName.Contains(SearchString) ||
employee.LastName.Contains(SearchString)
orderby employee.ID
select employee;
grdSearch.DataSource = FilteredEmployees;

Insert or Update Employee:

linqtosqlinsertupdate

Insert Update Employee

For inserting or updating an employee we used a stored procedure which will be called using LINQ as

EmployeeDataContext edc = new EmployeeDataContext();
foreach (DataGridViewRow row in grdInsertUpdate.Rows)
{
if (!row.IsNewRow &&
row.Cells[1].Value.ToString().Trim() != string.Empty &&
row.Cells[2].Value.ToString().Trim() != string.Empty)
{
edc.USP_Employee_InsertOrUpdate(
Convert.ToInt32(row.Cells[0].Value),
row.Cells[1].Value.ToString(),
row.Cells[2].Value.ToString());
}
}
grdInsertUpdate.DataSource = edc.Employees;

Delete an Employee:

linqtosqldelete

Delete Employee

Here we can give the option to delete the selected employee records. The stored procedure for deletion is called as follow

if (grdDelete.SelectedRows.Count > 0)
 {
EmployeeDataContext edc = new EmployeeDataContext();
foreach (DataGridViewRow row in grdDelete.SelectedRows)
{
if (Convert.ToInt32(row.Cells[0].Value) > 0)
{
edc.USP_Employee_Delete(Convert.ToInt32(row.Cells[0].Value));
}
}
grdDelete.DataSource = edc.Employees;
}

and thats the sample for using LINQ to SQL. Framework 3.5 has made life much easier and faster.

References:
http://msdn.microsoft.com/en-us/library/bb425822.aspx

Keep learing 🙂

Posted in LINQ To SQL | Tagged: , | 5 Comments »

Processes to XML using LINQ

Posted by codingsense on September 26, 2008


We have seen what is LINQ to objects and LINQ to XML now lets do some work that would need the combination of both.

Let us create an XML file which will consist of top 4 processes that are consuming high memory.

var MyProcess = from Proc in Process.GetProcesses()
where Proc.PagedMemorySize64 > 10000000
orderby Proc.PagedMemorySize64 descending
select new
XElement(“Process”,
new XElement(“Name”, Proc.ProcessName),
new XElement(“Memory”, Proc.PagedMemorySize64)
);

Console.WriteLine(new XElement(“Processes”, MyProcess.Take(4)));


Just have a closer look at what is being done. In MyProcess variable we get the list of all the process in the system those are taking more than 10000000 bytes of memory in desc order. While printing in Console.WriteLine we filter the top 4 process using Take Method.

Keep Learning 🙂

Posted in LINQ to XML | Tagged: , , | Leave a Comment »

Grouping XML Elements using Group By

Posted by codingsense on September 24, 2008

Since you have seen how to create an XML and fetch simple data from it, lets move to next level. In this sample we shall Group the elements and create our own XML from an existing XML.

Download Sample – 26Kb

Lets us consider a clientInfo XML which will store client Name and his Address(City,Area), now consider a situaltion where we would require to list all the employes grouped with their area name, How it can be done?. Here it goes.

XElement GroupAreas = new XElement("Areas",
            from client in ClientInfo.Elements()
            group client by client.Element("Address").Element("Area").Value into GroupedNames
            select new XElement(GroupedNames.Key,
                   GroupedNames.Elements("Name")
            ));

After this the clients will be grouped on their area name.

OutPut:

Happy Learning 🙂

Posted in LINQ to XML | Tagged: , , | 4 Comments »

Join XML using LINQ

Posted by codingsense on September 23, 2008

Hi All,

Today i have come with joining of 2 XML files using a relation using linq.

I will take a scenario where the clients are recognized by clientID , the basic information of each client (ID, Name and address) is stored at one place and the salary details (ID, Salary) will be stored at another place. Lets see what can be done If we need to join both these files into one.

 

Problem View::

Download Sample – 29kb

Create ClientInfo XML::

Here we shall create an XML of client data. Consider ID to be Unique Number (primary key). For each client we will have details like ID, name and address.

XElement ClientInfo = new XElement("Clients",
new XElement("Client",
new XElement("ID", "1"),
new XElement("Name", "Client1"),
new XElement("Address", "Mahalaxmi")
),
new XElement("Client",
new XElement("ID", "2"),
new XElement("Name", "Client2"),
new XElement("Address", "J.C.Road")
),
new XElement("Client",
new XElement("ID", "3"),
new XElement("Name", "Client3"),
new XElement("Address", "M.G.Road")
)
);

 

Output::

Create Salary XML::

Now we shall create an XML that will store the salary of each clients with their respective client ID.

XElement Salary = new XElement("Salaries",
new XElement("Salary",
new XElement("ID", "1"),
new XElement("Amount", "20000")
),
new XElement("Salary",
new XElement("ID", "3"),
new XElement("Amount", "30000")
),
new XElement("Salary",
new XElement("ID", "3"),
new XElement("Amount", "40000")
)
);

Output::


Join Both XML::

Lets try to join both the XML using the client ID and make them into one XML that will consist some elements of client info and some of salary .

XElement Join = new XElement("Clients",
from client in ClientInfo.Elements()
from sal in Salary.Elements()
where client.Element("ID").Value == sal.Element("ID").Value
select new XElement("Client", client.Descendants(), sal.Elements("Amount"))
);

Output:

Hope all of you got how to join two XML using an element as relation using LINQ.

Keep Exploring 🙂

Posted in LINQ to XML | Tagged: , , | Leave a Comment »

LINQ to XML basic sample

Posted by codingsense on September 22, 2008

The Microsoft definition:

LINQ to XML provides an in-memory XML programming interface that leverages the .NET Language-Integrated Query (LINQ) Framework. LINQ to XML uses the latest .NET Framework language capabilities and is comparable to an updated, redesigned Document Object Model (DOM) XML programming interface.

The namespace for dealing with XML is System.Xml.Linq

Download Sample – 26.4Kb

Basic Sample of LINQ to XML:

In this sample we will concentrate on how a XML can be created and accessed.
We will create a XML which will hold the client Information’s (ID,Name,Address).

Create a XML element:

XElement ClientInfo = new XElement("Clients",
new XElement("Client",
new XElement("ID", "1"),
new XElement("Name", "Client1"),
new XElement("Address", "Mahalaxmi")
),
new XElement("Client",
new XElement("ID", "2"),
new XElement("Name", "Client2"),
new XElement("Address", "J.C.Road")
),
new XElement("Client",
new XElement("ID", "3"),
new XElement("Name", "Client3"),
new XElement("Address", "M.G.Road")
)
);

Here XElement is an element of XML. It can be a single element or a child of another element or a parent with many more elements within it.

Output:

Only Client ID’s in a string Array::

Now lets try to take only client ID’s in a string array. Here is the code

string[] OnlyIDArr = (from Client in ClientInfo.Elements()
                      select Client.Element("ID").Value).ToArray<string>();

Output:

Create XML with only Client ID’s::

Here we will try to create an XML of only client ID’s

var OnlyID = from Client in ClientInfo.Elements()
             select new XElement("Client", Client.Element("ID"));

Output:

Nowadays XML is playing a vital role in many softwares and LINQ can be utilised to make it much easy, so try to explore it.

Keep Learning 🙂

Posted in LINQ to XML | Tagged: , , | 1 Comment »

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 »