Naveen's Weblog

Bridge to future

Archive for September, 2008

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: , , | Leave a 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 »

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: , , | 5 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: , , | 2 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: , , | Leave a Comment »