This blog is moved to
http://amalhashim.wordpress.com
Showing posts with label LINQ. Show all posts
Showing posts with label LINQ. Show all posts

Monday, May 2, 2011

DataTable to GenericList | C# and LINQ

Programming Microsoft® LINQ in Microsoft .NET Framework 4 
using System;
using System.Data;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
DataTable table = new DataTable
{
Columns = {
{"Id", typeof(int)},
{"Name", typeof(string)}
}
};

table.Rows.Add(1, "Amal");
table.Rows.Add(1, "Fousiya");
table.Rows.Add(1, "Munna");
table.Rows.Add(1, "Hussain");         

var listOfEmployees = from row in table.AsEnumerable()
select new Employee
{
Id = row.Field<int>("Id"),
Name = row.Field<String>("Name")
};

foreach (Employee emp in listOfEmployees)
{
Console.WriteLine("{0}   {1}", emp.Id, emp.Name);
}
}
}

class Employee
{
public int Id { get; set; }
public String Name { get; set; }
}
}

Sunday, April 11, 2010

LINQ Performance Benchmark

Yesterday I was reading “LINQ To Objects Using C# 4.0” by Troy Magennis and find a good LINQ usage example. I got curious about how the LINQ implementation will perform and thought of writing this article.

The example is related to an entity having 3 fields State, LastName and FirstName. The aim is to Group the objects by state and sort by LastName. For calculating the execution time I am using Stopwatch class in System.Diagnosis namespace.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.IO;

namespace ConsoleApplication2
{
public class Customer
{
public string State { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
}

class Program
{
static void Main(string[] args)
{
List<Customer> custList = FillListAndGetList();

Stopwatch sw = new Stopwatch();
sw.Start();
#region C# 2.0 Approach

///Sorting by LastName
custList.Sort(
delegate(Customer c1, Customer c2)
{
if (c1 != null && c2 != null)
return string.Compare(c1.LastName, c2.FirstName);
return 0;
});

///Sort and Groupby State [SortedDictionary]
SortedDictionary<string, List<Customer>>
sortedCust = new SortedDictionary<string, List<Customer>>();

foreach (Customer c in custList)
{
if (!sortedCust.ContainsKey(c.State))
sortedCust.Add(c.State, new List<Customer>());

sortedCust[c.State].Add(c);
}

foreach (KeyValuePair<string, List<Customer>>
pair in sortedCust)
{
Console.WriteLine("State : " + pair.Key);

foreach (Customer c in pair.Value)
Console.WriteLine("Last Name : {0}" +
"FirstName : {1} ", c.LastName,
c.FirstName);
}

#endregion

sw.Stop();
File.WriteAllLines("C20", new string[] { sw.ElapsedTicks.ToString() });

custList = FillListAndGetList();
sw.Reset();
sw.Start();

#region LINQ Approach

var query = from c in custList
orderby c.State, c.LastName
group c by c.State;

foreach (var group in query)
{
Console.WriteLine("State : " + group.Key);

foreach (Customer c in group)
Console.WriteLine("Last Name : {0}" +
"FirstName : {1} ", c.LastName,
c.FirstName);
}

#endregion

sw.Stop();
File.WriteAllLines("C20", new string[] { sw.ElapsedTicks.ToString() });
}

private static List<Customer> FillListAndGetList()
{
List<Customer> custList = new List<Customer>();
for (int i = 0; i < 1000000; i++)
{
Customer c = new Customer();
if (i % 2 == 0)
{
c.State = "State2";
c. FirstName = "FirstName2" + i.ToString();
c.LastName = "LastName2" + i.ToString();
}
else if (i % 3 == 0)
{
c.State = "State3";
c.FirstName = "FirstName3" + i.ToString();
c.LastName = "LastName3" + i.ToString();
}
else if(i % 7 == 0)
{
c.State = "State7";
c.FirstName = "FirstName7" + i.ToString();
c.LastName = "LastName7" + i.ToString();
}
else if (i % 11 == 0)
{
c.State = "State11";
c.FirstName = "FirstName11" + i.ToString();
c.LastName = "LastName11" + i.ToString();
}
else
{
c.State = "OtherState";
c.FirstName = "FirstName" + i.ToString();
c.LastName = "LastName" + i.ToString();
}

custList.Add(c);
}

return custList;
}
}
}

Once I ran the application, I got the following result.
C# 2.0 version : 627373008
LINQ version : 692116906
LINQ version has a slight performance problem, but compared to the chunk of code that has gone in 2.0 I think LINQ is far better.

Thursday, November 12, 2009

Basic usage of LINQ

We can use LINQ in any scenario where we want to iterate through a list of items. For example how about listing all types in the current application domain?

var asm = from a in AppDomain.CurrentDomain.GetAssemblies()
from type in a.GetExportedTypes()
select type;

foreach (var val in asm)
{
Console.WriteLine(val.Name);
}

How about listing all 3.5 assemblies order by length

var alist = asm.Where(x => x.Assembly.FullName.Contains("3.5.0.0")).
OrderByDescending(x => x.Name.Length);

foreach (var val in alist)
{
Console.WriteLine(val.Name);
}

Lets find the total count of types for each version

var vers = asm.Select(
x => x.Assembly.FullName.Split(",".ToCharArray())[1])
.GroupBy(y => y)
.Select(z => new { VerName = z.Key, Count = z.Count() });

foreach (var ver in vers)
{
Console.WriteLine(".NET {0} has {1} types\n", ver.VerName, ver.Count);
}
Interesting right?

Highest value in each group using LINQ

First of all, let me thank Suportim for explaining how to achieve this. For demonstrating I have created an employee class as shown below.

public class Employee
{
public string Name { get; set; }
public string Department { get; set; }
public int Salary { get; set; }
}
Our aim is to find those employee from each department who earns the most. Here I am manually creating some employee as shown below
List<Employee> employeeList = new List<Employee>();
employeeList.Add(new Employee() { Name = "John", Department = "Web", Salary = 1000 });
employeeList.Add(new Employee() { Name = "Frank", Department = "Web", Salary = 2000 });
employeeList.Add(new Employee() { Name = "Loyd", Department = "Web", Salary = 3000 });
employeeList.Add(new Employee() { Name = "Peter", Department = "IT", Salary = 1500 });
employeeList.Add(new Employee() { Name = "Tevez", Department = "IT", Salary = 2500 });
employeeList.Add(new Employee() { Name = "James", Department = "IT", Salary = 3500 });
employeeList.Add(new Employee() { Name = "Peter", Department = "Finance", Salary = 500 });
employeeList.Add(new Employee() { Name = "Tevez", Department = "Finance", Salary = 1500 });
employeeList.Add(new Employee() { Name = "Cameron", Department = "Finance", Salary = 3250 });
Now check the LINQ statement for finding the most earning employees for each department.
var employees = from e in employeeList
group e by e.Department into egrp
let max = egrp.Max(sal => sal.Salary)
select new
{
Department = egrp.Key,
Name = egrp.First(val=>val.Salary == max).Name,
Salary = egrp.First(val=>val.Salary == max).Salary
};
For demonstrating lets print the values to screen
foreach (var emp in employees)
{
Console.WriteLine("In Department {0}, Employee {1} has the highest salary {2}",
emp.Department, emp.Name, emp.Salary);
}
Hope this helps.