Thursday, December 27, 2012

LINQ Join Query

    class Employee  
    {  
      public int EmployeeID { get; set; }  
      public string EmployeeName { get; set; }  
      public int DeptId { get; set; }  
    }  
    class Dept  
    {  
      public int DeptId { get; set; }  
      public string DeptName { get; set; }  
    }  
      List<Dept> dept = new List<Dept>();  
      List<Employee> emp = new List<Employee>();  
      dept.AddRange(new Dept[]   
      {   
       new Dept{ DeptId=1, DeptName="IT" },  
       new Dept{ DeptId=2, DeptName="Engineering" }  
      });  
      emp.AddRange(new Employee[]  
      {  
       new Employee{EmployeeID = 1, DeptId = 1, EmployeeName="Sohail"},  
       new Employee{EmployeeID = 2, DeptId = 1, EmployeeName="Zeeshan"},  
       new Employee{EmployeeID = 3, DeptId = 2, EmployeeName="Zubair"},  
      });  
      emp.Join(dept, empRow => empRow.DeptId, deptRow => deptRow.DeptId, (selectEmpRow, selectDeptRow) =>  
       new  
       {  
         EmpId = selectEmpRow.EmployeeID,  
         EmpName = selectEmpRow.EmployeeName,  
         DeptName = selectDeptRow.DeptName  
       })  
       .ToList()  
       .ForEach(_ => { Console.WriteLine("{0} {1} {2}", _.EmpId, _.EmpName, _.DeptName); });  

Wednesday, December 26, 2012

Linq GroupBy with Aggregate functions

 List<Employee> empList = new List<Employee>();  
       empList.AddRange(new Employee[]   
       {   
         new Employee {EmpId =1, DeptId=1, Position="Director", Salary=100 },  
         new Employee {EmpId =2, DeptId=1, Position="Director", Salary = 120},  
         new Employee {EmpId =3, DeptId=1, Position="Software Engineer", Salary=50 },  
         new Employee {EmpId =4, DeptId=2, Position="Director", Salary=90 },  
         new Employee {EmpId =5, DeptId=2, Position="Director", Salary=100 },  
         new Employee {EmpId =6, DeptId=3, Position="HR Assistant", Salary=40 },  
         new Employee {EmpId =7, DeptId=3, Position="HR Manager", Salary=70},  
         new Employee {EmpId =8, DeptId=4, Position="IT Manager", Salary=85 },  
         new Employee {EmpId =8, DeptId=4, Position="IT Assistant", Salary=40 }  
       });  
   
       /*  
        * The highest salary from the each dept per position  
       */  
       empList.GroupBy(_ => new { _.DeptId, _.Position })  
         .Select(_ => new  
         {  
           MaximumSalary = _.Max(deptPositionGroup => deptPositionGroup.Salary),  
           DepartmentId = _.Key.DeptId,  
           Position = _.Key.Position  
         }).ToList()  
         .ForEach(selectedRecords =>  
         {  
           Console.WriteLine("{0} {1} {2}", selectedRecords.DepartmentId, selectedRecords.Position, selectedRecords.MaximumSalary);  
         });  
   
       /*Average salary from each dept per position */  
   
       Console.WriteLine();  
       Console.WriteLine();  
       Console.WriteLine();  
       empList.GroupBy(_ => new { _.DeptId, _.Position })  
               .Select(_ => new  
               {  
                 AverageSalary = _.Average(deptPositionGroup => deptPositionGroup.Salary),  
                 DepartmentId = _.Key.DeptId,  
                 Position = _.Key.Position  
               }).ToList()  
               .ForEach(selectedRecords =>  
               {  
                 Console.WriteLine("{0} {1} {2}", selectedRecords.DepartmentId, selectedRecords.Position, selectedRecords.AverageSalary);  
               });  
       Console.WriteLine();  
       Console.WriteLine();  
       Console.WriteLine();  
       /*Average salary from each dept */  
       empList.GroupBy(_ => _.DeptId)  
               .Select(_ => new  
               {  
                 AverageSalary = _.Average(deptPositionGroup => deptPositionGroup.Salary),  
                 DepartmentId = _.Key,  
               }).ToList()  
               .ForEach(selectedRecords =>  
               {  
                 Console.WriteLine("{0} {1}", selectedRecords.DepartmentId, selectedRecords.AverageSalary);  
               });  

Tuesday, December 18, 2012

Convert Dictionary into Strongly Typed Class


There are few things you have to consider before conversion of dictionary into strongly typed class object.

1 - To detect in which class you want to convert into dictionary. For this purpose you need generic (Template) where you will specify in which class you want to convert.

2 - Get the properties of the strongly typed class using reflection.

3 - Create the object of the Generic . and get the reference of it.

4 - Iterate the properties of object and search the dictionary contains that field or column, if its find and writeable then set the value using reflection but cast the values into the strongly typed of a column too.

Here's the demo.

   class Emp {
      public string Name { get; set; }
      public string TechnologyExpert { get; set; }
      public int Salary { get; set; }
      public override string ToString(){
         return Name + "-----" + TechnologyExpert + "-----" + Salary;
      }
   }
   class Cust{
      public string Name { get; set; }
      public string Company { get; set; }
      public override string ToString(){
         return Name + "------" + Company;
      }
   }

/// Please use angle bracket here too.
   class ConvertIntoStronglyTyped  where T: new() {
      public static T ConvertMe(Dictionary objectDict)
      {
         var properties = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly);
       
         Object obj = new T();
       
         foreach (var property in properties)
            if (property.CanWrite && objectDict.ContainsKey(property.Name))            
               property.SetValue(obj, Cast(property.PropertyType.FullName, objectDict[property.Name]), null);                  

         return (T)obj;
      }

      private static object Cast(string propertyTypeName, object value) {
         string strFullName = typeof(string).FullName;
         string intFullName = typeof(int).FullName;
         string floatFullName = typeof(float).FullName;

         if (strFullName == propertyTypeName)   return value.ToString();
         if (intFullName == propertyTypeName)   return int.Parse(value.ToString());
         if (floatFullName == propertyTypeName) return int.Parse(value.ToString());
       
         return value;
      }
   }

Execute the code.

class Program
   {
      static void Main(string[] args)
      {
         Dictionary consolidatedValues = new Dictionary();
       
         consolidatedValues.Add("Name", "Sohail");
         consolidatedValues.Add("TechnologyExpert", "C#");
         consolidatedValues.Add("Salary", "200");
         consolidatedValues.Add("Company", "ABC .Com");

// I noticed the less than greater than bracket is not visible, use simple the angle brackets.
         Emp emp = ConvertIntoStronglyTyped&ltEmp&gt.ConvertMe(consolidatedValues);

         Cust cust = ConvertIntoStronglyTyped.ConvertMe(consolidatedValues);
         Console.WriteLine(emp);
         Console.WriteLine(cust);
      }
   }

Please let me know incase you are facing issue and have more questions regarding the reflections or generics.