March 2010 - Posts - Raj Kaimal

March 2010 - Posts

Easy way to update models in your ASP.NET MVC business layer

Brad Wilson just mentioned that the MVC Futures library has a static ModelCopier class with a CopyModel(object from, object to) static method. It uses reflection to match properties with the same name and compatible types.

In short, instead of manually copying over properties as shown here:

public void Save(EmployeeViewModel employeeViewModel)
{
    var employee = (from emp in dataContext.Employees
                   where emp.EmployeeID == employeeViewModel.EmployeeID
                   select emp).SingleOrDefault();
 
    if (employee != null)
    {
        employee.Address = employeeViewModel.Address;
        employee.Salary = employeeViewModel.Salary;
        employee.Title = employeeViewModel.Title;
    }
    dataContext.SubmitChanges();
}

you do this:

public void Save(EmployeeViewModel employeeViewModel)
{
    var employee = (from emp in dataContext.Employees
                    where emp.EmployeeID == employeeViewModel.EmployeeID
                    select emp).SingleOrDefault();
 
    if (employee != null)
    {
        ModelCopier.CopyModel(employeeViewModel, employee);
    }
    dataContext.SubmitChanges();
}

Beautiful, isn’t it?

Posted by rajbk | 8 comment(s)
Filed under: , , ,

How LINQ to Object statements work

This post goes into detail as to now LINQ statements work when querying a collection of objects.

This topic assumes you have an understanding of how generics, delegates, implicitly typed variables, lambda expressions, object/collection initializers, extension methods and the yield statement work. I would also recommend you read my previous two posts:

We will start by writing some methods to filter a collection of data.
Assume we have an Employee class like so:

public class Employee {
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string LastName {get; set;}
    public string Country { get; set; }
}

and a collection of employees like so:

 
var employees = new List<Employee> {
    new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
    new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
    new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
    new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" },
};


Filtering
We wish to  find all employees that have an even ID. We could start off by writing a method that takes in a list of employees and returns a filtered list of employees with an even ID.

 
static List<Employee> GetEmployeesWithEvenID(List<Employee> employees) {
    var filteredEmployees = new List<Employee>();
    foreach (Employee emp in employees) {
        if (emp.ID % 2 == 0) {
            filteredEmployees.Add(emp);
        }
    }
    return filteredEmployees;
}


The method can be rewritten to return an IEnumerable<Employee> using the yield return keyword.

static IEnumerable<Employee> GetEmployeesWithEvenID(IEnumerable<Employee> employees) {
    foreach (Employee emp in employees) {
        if (emp.ID % 2 == 0) {
            yield return emp;
        }
    }
}

We put these together in a console application.

using System;
using System.Collections.Generic;
//No System.Linq
 
public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" },
        };
        var filteredEmployees = GetEmployeesWithEvenID(employees);
 
        foreach (Employee emp in filteredEmployees) {
            Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 
                emp.ID, emp.FirstName, emp.LastName, emp.Country); 
           }        
 
        Console.ReadLine();
    }
    
    static IEnumerable<Employee> GetEmployeesWithEvenID(IEnumerable<Employee> employees) {
        foreach (Employee emp in employees) {
            if (emp.ID % 2 == 0) {
                yield return emp;
            }
        }
    }    
}
 
public class Employee {
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string LastName {get; set;}
    public string Country { get; set; }
}

Output:

ID 2 First_Name Jim Last_Name Ashlock Country UK
ID 4 First_Name Jill Last_Name Anderson Country AUS

Our filtering method is too specific. Let us change it so that it is capable of doing different types of filtering and lets give our method the name Where ;-)
We will add another parameter to our Where method. This additional parameter will be a delegate with the following declaration.

public delegate bool Filter(Employee emp);

The idea is that the delegate parameter in our Where method will point to a method that contains the logic to do our filtering thereby freeing our Where method from any dependency. The method is shown below:

static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) {
    foreach (Employee emp in employees) {
        if (filter(emp)) {
            yield return emp;
        }
    }
}
Making the change to our app, we create a new instance of the Filter delegate on line 14 with a target set to the method EmployeeHasEvenId. Running the code will produce the same output.
public delegate bool Filter(Employee emp);
 
public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
        var filterDelegate = new Filter(EmployeeHasEvenId);
        var filteredEmployees = Where(employees, filterDelegate);
 
        foreach (Employee emp in filteredEmployees) {
            Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 
                emp.ID, emp.FirstName, emp.LastName, emp.Country);
           }
        Console.ReadLine();
    }
    
    static bool EmployeeHasEvenId(Employee emp) {
        return emp.ID % 2 == 0;
    }
    
    static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) {
        foreach (Employee emp in employees) {
            if (filter(emp)) {
                yield return emp;
            }
        }
    }
}
 
public class Employee {
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string LastName {get; set;}
    public string Country { get; set; }
}


Lets use lambda expressions to inline the contents of the EmployeeHasEvenId method in place of the method. The next code snippet shows this change (see line 15).  For brevity, the Employee class declaration has been skipped.

public delegate bool Filter(Employee emp);
 
public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1,     FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2,     FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3,     FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4,     FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
        var filterDelegate = new Filter(EmployeeHasEvenId);
        var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0);
 
        foreach (Employee emp in filteredEmployees) {
            Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 
                emp.ID, emp.FirstName, emp.LastName, emp.Country);
           }
        Console.ReadLine();
    }
    
    static bool EmployeeHasEvenId(Employee emp) {
        return emp.ID % 2 == 0;
    }
    
    static IEnumerable<Employee> Where(IEnumerable<Employee> employees, Filter filter) {
        foreach (Employee emp in employees) {
            if (filter(emp)) {
                yield return emp;
            }
        }
    }
}
 

The output displays the same two employees. 

Our Where method is too restricted since it works with a collection of Employees only. Lets change it so that it works with any IEnumerable<T>. In addition, you may recall from my previous post,  that .NET 3.5 comes with a lot of predefined delegates including

public delegate TResult Func<T, TResult>(T arg);

We will get rid of our Filter delegate and use the one above instead. We apply these two changes to our code.

public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
 
        var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0);
 
        foreach (Employee emp in filteredEmployees) {
            Console.WriteLine("ID {0} First_Name {1} Last_Name {2} Country {3}", 
                emp.ID, emp.FirstName, emp.LastName, emp.Country);
           }
        Console.ReadLine();
    }
    
    static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) {
        foreach (var x in source) {
            if (filter(x)) {
                yield return x;
            }
        }
    }
}

We have successfully implemented a way to filter any IEnumerable<T> based on a  filter criteria.

Projection
Now lets enumerate on the items in the IEnumerable<Employee> we got from the Where method and copy them into a new IEnumerable<EmployeeFormatted>. The EmployeeFormatted class will only have a FullName and ID property.

public class EmployeeFormatted {
    public int ID { get; set; }
    public string FullName {get; set;}
}

We could “project” our existing IEnumerable<Employee> into a new collection of IEnumerable<EmployeeFormatted> with the help of a new method. We will call this method Select ;-)

static IEnumerable<EmployeeFormatted> Select(IEnumerable<Employee> employees) {
    foreach (var emp in employees) {
        yield return new EmployeeFormatted {
            ID = emp.ID,
            FullName = emp.LastName + ", " + emp.FirstName
        };
    }
}

The changes are applied to our app.

public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
 
        var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0);
        var formattedEmployees = Select(filteredEmployees);
 
        foreach (EmployeeFormatted emp in formattedEmployees) {
            Console.WriteLine("ID {0} Full_Name {1}", 
                emp.ID, emp.FullName);
           }
        Console.ReadLine();
    }
 
    static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) {
        foreach (var x in source) {
            if (filter(x)) {
                yield return x;
            }
        }
    }
    
    static IEnumerable<EmployeeFormatted> Select(IEnumerable<Employee> employees) {
        foreach (var emp in employees) {
            yield return new EmployeeFormatted {
                ID = emp.ID,
                FullName = emp.LastName + ", " + emp.FirstName
            };
        }
    }
}
 
public class Employee {
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string LastName {get; set;}
    public string Country { get; set; }
}
 
public class EmployeeFormatted {
    public int ID { get; set; }
    public string FullName {get; set;}
}

Output:

ID 2 Full_Name Ashlock, Jim
ID 4 Full_Name Anderson, Jill

We have successfully selected employees who have an even ID and then shaped our data with the help of the Select method so that the final result is an IEnumerable<EmployeeFormatted>

Lets make our Select method more generic so that the user is given the freedom to shape what the output would look like. We can do this, like before, with lambda expressions. Our Select method is changed to accept a delegate as shown below. TSource will be the type of data that comes in and TResult will be the type the user chooses (shape of data) as returned from the selector delegate.

 
static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector) {
    foreach (var x in source) {
        yield return selector(x);
    }
}

We see the new changes to our app. On line 15, we use lambda expression to specify the shape of the data. In this case the shape will be of type EmployeeFormatted.

public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
 
        var filteredEmployees = Where(employees, emp => emp.ID % 2 == 0);
        var formattedEmployees = Select(filteredEmployees, (emp) =>
                                    new EmployeeFormatted {
                                        ID = emp.ID,
                                        FullName = emp.LastName + ", " + emp.FirstName
                                 });
 
        foreach (EmployeeFormatted emp in formattedEmployees) {
            Console.WriteLine("ID {0} Full_Name {1}", 
                emp.ID, emp.FullName);
           }
        Console.ReadLine();
    }
    
    static IEnumerable<T> Where<T>(IEnumerable<T> source, Func<T, bool> filter) {
        foreach (var x in source) {
            if (filter(x)) {
                yield return x;
            }
        }
    }
    
    static IEnumerable<TResult> Select<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, TResult> selector) {
        foreach (var x in source) {
            yield return selector(x);
        }
    }
}


The code outputs the same result as before. On line 14 we filter our data and on line 15 we project our data.

What if we wanted to be more expressive and concise? We could combine both line 14 and 15 into one line as shown below. Assuming you had to perform several operations like this on our collection, you would end up with some very unreadable code!

var formattedEmployees = Select(Where(employees, emp => emp.ID % 2 == 0), (emp) =>
                            new EmployeeFormatted {
                                ID = emp.ID,
                                FullName = emp.LastName + ", " + emp.FirstName
                         });

A cleaner way to write this would be to give the appearance that the Select and Where methods were part of the IEnumerable<T>. This is exactly what extension methods give us. Extension methods have to be defined in a static class. Let us make the Select and Where extension methods on IEnumerable<T>

public static class MyExtensionMethods {
        static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) {
        foreach (var x in source) {
            if (filter(x)) {
                yield return x;
            }
        }
    }
    
    static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) {
        foreach (var x in source) {
            yield return selector(x);
        }
    }
}

The creation of the extension method makes the syntax much cleaner as shown below. We can write as many extension methods as we want and keep on chaining them using this technique.

var formattedEmployees =  employees
                            .Where(emp => emp.ID % 2 == 0)
                            .Select (emp => new EmployeeFormatted { ID = emp.ID, FullName = emp.LastName + ", " + emp.FirstName });

Making these changes and running our code produces the same result.

using System;
using System.Collections.Generic;
 
public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
 
        var formattedEmployees =  employees
                                    .Where(emp => emp.ID % 2 == 0)
                                    .Select (emp => 
                                        new EmployeeFormatted {
                                            ID = emp.ID,
                                            FullName = emp.LastName + ", " + emp.FirstName
                                        }
                                     );
 
        foreach (EmployeeFormatted emp in formattedEmployees) {
            Console.WriteLine("ID {0} Full_Name {1}", 
                emp.ID, emp.FullName);
           }
        Console.ReadLine();
    }
}
 
public static class MyExtensionMethods {
        static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) {
        foreach (var x in source) {
            if (filter(x)) {
                yield return x;
            }
        }
    }
    
    static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) {
        foreach (var x in source) {
            yield return selector(x);
        }
    }
}
 
public class Employee {
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string LastName {get; set;}
    public string Country { get; set; }
}
 
public class EmployeeFormatted {
    public int ID { get; set; }
    public string FullName {get; set;}
}

Let’s change our code to return a collection of anonymous types and get rid of the EmployeeFormatted type. We see that the code produces the same output.

using System;
using System.Collections.Generic;
 
public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
 
        var formattedEmployees =  employees
                                    .Where(emp => emp.ID % 2 == 0)
                                    .Select (emp => 
                                        new  {
                                            ID = emp.ID,
                                            FullName = emp.LastName + ", " + emp.FirstName
                                        }
                                     );
 
        foreach (var emp in formattedEmployees) {
            Console.WriteLine("ID {0} Full_Name {1}", 
                emp.ID, emp.FullName);
           }
        Console.ReadLine();
    }
}
 
public static class MyExtensionMethods {
    public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> filter) {
        foreach (var x in source) {
            if (filter(x)) {
                yield return x;
            }
        }
    }
    
    public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector) {
        foreach (var x in source) {
            yield return selector(x);
        }
    }
}
 
public class Employee {
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string LastName {get; set;}
    public string Country { get; set; }
}

To be more expressive, C# allows us to write our extension method calls as a query expression. Line 16 can be rewritten a query expression like so:

var formattedEmployees =  from emp in employees
                          where emp.ID % 2 == 0
                          select new {
                              ID = emp.ID,
                              FullName = emp.LastName + ", " + emp.FirstName
                          };

When the compiler encounters an expression like the above, it simply rewrites it as calls to our extension methods. 

So far we have been using our extension methods. The System.Linq namespace contains several extension methods for objects that implement the IEnumerable<T>. You can see a listing of these methods in the Enumerable class in the System.Linq namespace.

Let’s get rid of our extension methods (which I purposefully wrote to be of the same signature as the ones in the Enumerable class) and use the ones provided in the Enumerable class. Our final code is shown below:

using System;
using System.Collections.Generic;
using System.Linq; //Added
 
public class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        var employees = new List<Employee> {
            new Employee { ID = 1, FirstName = "John", LastName = "Wright",   Country = "USA" },  
            new Employee { ID = 2, FirstName = "Jim",  LastName = "Ashlock",  Country = "UK"  },
            new Employee { ID = 3, FirstName = "Jane", LastName = "Jackson",  Country = "CHE" }, 
            new Employee { ID = 4, FirstName = "Jill", LastName = "Anderson", Country = "AUS" }
        };
 
        var formattedEmployees =  from emp in employees
                                  where emp.ID % 2 == 0
                                  select new {
                                      ID = emp.ID,
                                    FullName = emp.LastName + ", " + emp.FirstName
                                  };
 
        foreach (var emp in formattedEmployees) {
            Console.WriteLine("ID {0} Full_Name {1}", 
                emp.ID, emp.FullName);
           }
        Console.ReadLine();
    }
}
 
public class Employee {
    public int ID { get; set;}
    public string FirstName { get; set;}
    public string LastName {get; set;}
    public string Country { get; set; }
}
 
public class EmployeeFormatted {
    public int ID { get; set; }
    public string FullName {get; set;}
}

This post has shown you a basic overview of LINQ to Objects work by showning you how an expression is converted to a sequence of calls to extension methods when working directly with objects. It gets more interesting when working with LINQ to SQL where an expression tree is constructed – an in memory data representation of the expression. The C# compiler compiles these expressions into code that builds an expression tree at runtime. The provider can then traverse the expression tree and generate the appropriate SQL query. You can read more about expression trees in this MSDN article.

Posted by rajbk | 2 comment(s)
Filed under: , , ,

Using delegates in C# (Part 2)

Part 1 of this post can be read here.

We are now about to see the different syntaxes for invoking a delegate and some c# syntactic sugar which allows you to code faster. We have the following console application.

   1: public delegate double Operation(double x, double y);
   2:  
   3: public class Program
   4: {
   5:     [STAThread]
   6:     static void Main(string[] args)
   7:     {
   8:         Operation op1 = new Operation(Division);
   9:         double result = op1.Invoke(10, 5);
  10:         
  11:         Console.WriteLine(result);
  12:         Console.ReadLine();
  13:     }
  14:     
  15:     static double Division(double x, double y) {
  16:         return x / y;
  17:     }
  18: }

Line 1 defines a delegate type called Operation with input parameters (double x, double y) and a return type of double.
On Line 8, we create an instance of this delegate and set the target to be a static method called Division (Line 15)
On Line 9, we invoke the delegate (one entry in the invocation list).
The program outputs 2 when run.

The language provides shortcuts for creating a delegate and invoking it (see line 9 and 11). Line 9 is a syntactical shortcut for creating an instance of the Delegate. The C# compiler will infer on its own what the delegate type is and produces intermediate language that creates a new instance of that delegate. Line 11 uses a a syntactical shortcut for invoking the delegate by removing the Invoke method. The compiler sees the line and generates intermediate language which invokes the delegate. When this code is compiled, the generated IL will look exactly like the IL of the compiled code above.

   1: public delegate double Operation(double x, double y);
   2:  
   3: public class Program
   4: {
   5:     [STAThread]
   6:     static void Main(string[] args)
   7:     {
   8:         //shortcut constructor syntax
   9:         Operation op1 = Division;
  10:         //shortcut invoke syntax
  11:         double result = op1(10, 2);
  12:         
  13:         Console.WriteLine(result);
  14:         Console.ReadLine();
  15:     }
  16:     
  17:     static double Division(double x, double y) {
  18:         return x / y;
  19:     }
  20: }

C# 2.0 introduced Anonymous Methods. Anonymous methods avoid the need to create a separate method that contains the same signature as the delegate type. Instead you write the method body in-line.

There is an interesting fact about Anonymous methods and closures which won’t be covered here. Use your favorite search engine ;-)

We rewrite our code to use anonymous methods (see line 9):

   1: public delegate double Operation(double x, double y);
   2:  
   3: public class Program
   4: {
   5:     [STAThread]
   6:     static void Main(string[] args)
   7:     {
   8:         //Anonymous method
   9:         Operation op1 = delegate(double x, double y) {
  10:             return x / y;
  11:         };
  12:         double result = op1(10, 2);
  13:         
  14:         Console.WriteLine(result);
  15:         Console.ReadLine();
  16:     }
  17:     
  18:     static double Division(double x, double y) {
  19:         return x / y;
  20:     }
  21: }

We could rewrite our delegate to be of a generic type like so (see line 2 and line 9). You will see why soon.

   1: //Generic delegate
   2: public delegate T Operation<T>(T x, T y);
   3:  
   4: public class Program
   5: {
   6:     [STAThread]
   7:     static void Main(string[] args)
   8:     {
   9:         Operation<double> op1 = delegate(double x, double y) {
  10:             return x / y;
  11:         };
  12:         double result = op1(10, 2);
  13:         
  14:         Console.WriteLine(result);
  15:         Console.ReadLine();
  16:     }
  17:     
  18:     static double Division(double x, double y) {
  19:         return x / y;
  20:     }
  21: }

The .NET 3.5 framework introduced a whole set of predefined delegates for us including

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);


Our code can be modified to use this delegate instead of the one we declared. Our delegate declaration has been removed and line 7 has been changed to use the Func delegate type.

   1: public class Program
   2: {
   3:     [STAThread]
   4:     static void Main(string[] args)
   5:     {
   6:         //Func is a delegate defined in the .NET 3.5 framework
   7:         Func<double, double, double> op1 = delegate (double x, double y) {
   8:             return x / y;
   9:         };
  10:         double result = op1(10, 2);
  11:         
  12:         Console.WriteLine(result);
  13:         Console.ReadLine();
  14:     }
  15:     
  16:     static double Division(double x, double y) {
  17:         return x / y;
  18:     }
  19: }

.NET 3.5 also introduced lambda expressions. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. We change our code to use lambda expressions.

   1: public class Program
   2: {
   3:     [STAThread]
   4:     static void Main(string[] args)
   5:     {
   6:         //lambda expression
   7:         Func<double, double, double> op1 = (x, y) => x / y;
   8:         double result = op1(10, 2);
   9:         
  10:         Console.WriteLine(result);
  11:         Console.ReadLine();
  12:     }
  13: }

As a side note, C# 3.0 introduced the keyword var (implicitly typed local variable) where the type of the variable is inferred based on the type of the associated initializer expression. We can rewrite our code to use var as shown below (line 7).  The implicitly typed local variable op1 is inferred to be a delegate of type Func<double, double, double> at compile time.

   1: public class Program
   2: {
   3:     [STAThread]
   4:     static void Main(string[] args)
   5:     {
   6:         //implicitly typed local variable
   7:         var op1 = new Func<double, double, double>((x, y) => x / y);
   8:         double result = op1(10, 2);
   9:         
  10:         Console.WriteLine(result);
  11:         Console.ReadLine();
  12:     }
  13: }

You have seen how we can write code in fewer lines by using a combination of the Func delegate type, implicitly typed local variables and lambda expressions.

Edit Mar 29, 2010 : Fixed typos

Posted by rajbk | 11 comment(s)
Filed under: , , ,

Using Delegates in C# (Part 1)

This post provides a very basic introduction of delegates in C#.

Part 2 of this post can be read here.

A delegate is a class that is derived from System.Delegate.  It contains a list of one or more methods called an invocation list. When a delegate instance is “invoked” with the arguments as defined in the signature of the delegate, each of the methods in the invocation list gets invoked with the arguments. The code below shows example with static and instance methods respectively:

Static Methods

   1: using System;
   2: using System.Linq;
   3: using System.Collections.Generic;
   4:  
   5: public delegate void SayName(string name);
   6:  
   7: public class Program
   8: {
   9:     [STAThread]
  10:     static void Main(string[] args)
  11:     {
  12:         SayName englishDelegate = new SayName(SayNameInEnglish);
  13:         SayName frenchDelegate = new SayName(SayNameInFrench);
  14:         SayName combinedDelegate =(SayName)Delegate.Combine(englishDelegate, frenchDelegate);
  15:         
  16:         combinedDelegate.Invoke("Tom");
  17:         Console.ReadLine();
  18:     }
  19:     
  20:     static void SayNameInFrench(string name) {
  21:         Console.WriteLine("Je m'appelle " + name);
  22:     }
  23:     
  24:     static void SayNameInEnglish(string name) {
  25:         Console.WriteLine("My name is " + name);
  26:     }
  27: }

We have declared a delegate of type SayName with return type of void and taking an input parameter of name of type string.

On line 12, we create a new instance of this delegate which refers to a static method - SayNameInEnglishSayNameInEnglish has the same return type and parameter list as the delegate declaration.  Once a delegate is instantiated, the instance will always refer to the same target. Delegates are immutable.
On line 13, we create a new instance of the delegate but point to a different static method.
As you may recall, a delegate instance encapsulates an invocation list. You create an invocation list by combining delegates using the Delegate.Combine method (there is an easier syntax as you will see later). When two non null delegate instances are combined, their invocation lists get combined to form a new invocation list. This is done in line 14. 
On line 16, we invoke the delegate with the Invoke method and pass in the required string parameter. Since the delegate has an invocation list with two entries, each of the method in the invocation list is invoked.
If an unhandled exception occurs during the invocation of one of these methods, the exception gets bubbled up to the line where the invocation was made (line 16).
If a delegate is null and you try to invoke it, you will get a System.NullReferenceException.

We see the following output when the method is run:

My name is Tom
Je m'apelle Tom

Instance Methods

The code below outputs the same results as before. The only difference here is we are creating delegates that point to a target object (an instance of Translator) and instance methods which have the same signature as the delegate type. The target object can never be null. We also use the short cut syntax += to combine the delegates instead of Delegate.Combine.

   1: public delegate void SayName(string name);
   2:  
   3: public class Program
   4: {
   5:     [STAThread]
   6:     static void Main(string[] args)
   7:     {
   8:         Translator translator = new Translator();
   9:         SayName combinedDelegate = new SayName(translator.SayNameInEnglish);
  10:         combinedDelegate += new SayName(translator.SayNameInFrench);
  11:  
  12:         combinedDelegate.Invoke("Tom");
  13:         Console.ReadLine();
  14:     }
  15: }
  16:  
  17: public class Translator {
  18:     public void SayNameInFrench(string name) {
  19:         Console.WriteLine("Je m'appelle " + name);
  20:     }
  21:     
  22:     public void SayNameInEnglish(string name) {
  23:         Console.WriteLine("My name is " + name);
  24:     }
  25: }

A delegate can be removed from a combination of delegates by using the –= operator. Removing a delegate from an empty list or removing a delegate that does not exist in a non empty list will not result in an exception. Delegates are invoked synchronously using the Invoke method. We can also invoke them asynchronously using the BeginInvoke and EndInvoke methods which are compiler generated.

Posted by rajbk | 8 comment(s)
Filed under: , , ,

Joins in LINQ to SQL

The following post shows how to write different types of joins in LINQ to SQL. I am using the Northwind database and LINQ to SQL for these examples.

NorthwindDataContext dataContext = new NorthwindDataContext();

Inner Join
var q1 = from c in dataContext.Customers
         join o in dataContext.Orders on c.CustomerID equals o.CustomerID
         select new
         {
             c.CustomerID,
             c.ContactName,
             o.OrderID,
             o.OrderDate
         };
SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]
FROM [dbo].[Customers] AS [t0]
INNER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID]

Left Join
var q2 = from c in dataContext.Customers
         join o in dataContext.Orders on c.CustomerID equals o.CustomerID into g
         from a in g.DefaultIfEmpty()
         select new
         {
             c.CustomerID,
             c.ContactName,
             a.OrderID,
             a.OrderDate
         };
SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]
FROM [dbo].[Customers] AS [t0]
LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON [t0].[CustomerID] = [t1].[CustomerID]


Inner Join on multiple
//We mark our anonymous type properties as a and b otherwise
//we get the compiler error "Type inferencce failed in the call to 'Join’
 
 
var q3 = from c in dataContext.Customers
         join o in dataContext.Orders on new { a = c.CustomerID, b = c.Country } equals new { a = o.CustomerID, b = "USA" }
         select new
         {
             c.CustomerID,
             c.ContactName,
             o.OrderID,
             o.OrderDate
         };
SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]
FROM [dbo].[Customers] AS [t0]
INNER JOIN [dbo].[Orders] AS [t1] ON ([t0].[CustomerID] = [t1].[CustomerID]) AND ([t0].[Country] = @p0)

Inner Join on multiple with ‘OR’ clause
var q4 = from c in dataContext.Customers
         from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA")
         select new
         {
             c.CustomerID,
             c.ContactName,
             o.OrderID,
             o.OrderDate
         };
SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID], [t1].[OrderDate]
FROM [dbo].[Customers] AS [t0], [dbo].[Orders] AS [t1]
WHERE ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0)


Left Join on multiple with ‘OR’ clause
var q5 = from c in dataContext.Customers
         from o in dataContext.Orders.Where(a => a.CustomerID == c.CustomerID || c.Country == "USA").DefaultIfEmpty()
         select new
         {
             c.CustomerID,
             c.ContactName,
             o.OrderID,
             o.OrderDate
         };
SELECT [t0].[CustomerID], [t0].[ContactName], [t1].[OrderID] AS [OrderID], [t1].[OrderDate] AS [OrderDate]
FROM [dbo].[Customers] AS [t0]
LEFT OUTER JOIN [dbo].[Orders] AS [t1] ON ([t1].[CustomerID] = [t0].[CustomerID]) OR ([t0].[Country] = @p0)

Posted by rajbk | 5 comment(s)
Filed under: , , ,
More Posts