C# Linq

More Lambda syntax, replacing grouping method or anonymous methods

It´s been a long while since I posted something, I have som cool Lambda syntax that I coded today that I would like to share with my readers.

The problem

I have a helper metod that takes a method delegate as parameter, the delegate looks like this.

delegate void MethodDelegate(TParam param)

I´m using this with some other stuff to create thread call´s in my winform applications. It could be calls like CreateUser(User user), the method always takes one parameter. Anyway my Crud classes have some method that uses two parameters like UpdateUser(User user, string key).

Now how do I use this easily with my Delegate, I could write a method that looks like this (I have left out the generic stuff to don´t make this to complex):

private void UpdateUser(User user)
{
    CrudService.UpdateUser(user, user.UserId);
}

And use that method with the delagete call (PassMethod), or you could use a anonymous method like this:

PassMethod(delegate { crudService.UpdateUser(user, user.UserId.ToString()); });

For some reason I prefer a nice Lambda syntax instead like this:

PassMethod(user, param => crudService.UpdateUser(user, user.UserId.ToString()));

Select instead of foreach

A quick sample demonstrating the power of Lambda. A realy stupid one I want to append all Account name in to a StringBuilder object and show the result in a MessageBox.

The foreach way

var accounts = crudClient.Read<Account>();
var message = new StringBuilder();
foreach (var account in accounts)
    message.Append(account.Name);
MessageBox.Show(string.Format("Property values:{0}", message));

 

The Lambda way

var accounts = crudClient.Read<Account>();
var message = new StringBuilder();
accounts.Select(a => message.Append(a.Name)).ToList();
MessageBox.Show(string.Format("Property values:{0}", message));

It is realy a stupid example, but it should give you a hint of the Lambda/Linq power. Observe that I have to call the ToList() method otherwise the projection on accounts never fires.

LinqToSql about DataContext

Linq is very new so it´s not that easy to fully understand how every object is supposed to be used. What I (and others) wonder is how to use the DataContext object. I have used one static DataContext using the singleton pattern. But I found limitations with this, googling around I found a very interesting article that Dino Esposito one of the architects of Linq wrote. Here some of it you can read the whole article here:

In general, a DataContext instance is designed to last for one unit of work however your application defines that term. It is not recommended to maintain a DataContext live for more such as stored in a singleton object. DataContext should be kind of using an ADO.NET connection: you use always new DbConnection objects but reuse command text and parameters. You never keep a connection open for a long time and don’t pass it around tiers.

Dino Esposito

http://weblogs.asp.net/despos/archive/2008/03/19/more-on-datacontext-in-hopefully-a-realistic-world.aspx

With Linq came… Part two

Lambda Expression

Lambda Expression is a kind of syntax shortcut for a anonymous method, the operator for Lambda is => and should be read as goto, the operator separates the inparameter on the left side and the lambda body on the right side. A sample of an lambda expression:

int[] arrInt = {1,2,3,4,5,6,7,8,9,10};

//Lambda Expression
var aa = arrInt.Where(s => s % 2 == 0);

foreach (var item in aa)
{
    Console.WriteLine("{0}", item);
}

This code will write out every even number in the int array arrInt. From the begining lambda expression was the syntax to be used with Linq, but when the Developer team let diffrent kind of users test this, it was considered as not good enough. Query expression was the solution for that, with this you can write the same thing this way:

int[] arrInt = {1,2,3,4,5,6,7,8,9,10};

//Query Expression
var aa = from s in arrInt
where s % 2 == 0
select s;

foreach (var item in aa)
{
    Console.WriteLine("{0}", item);
}

This will do exact the same thing, query expression syntax is more readable then lambda, lambda is nice when the query is very simple. But where did the Where method came from you may ask does int[] array now have a Where method? Next subject will explain this.

Extension Methods

Look at this screenshoot:

Intellisense says it all, those methods that has the symbol is an extension method and not really a part of the int array class. Many extension methods has been added by the Microsoft developer team to arrays and collections to be used with Linq. But you can also add extension methods yourself. I show you how, here a funny example in a simple console application I want to extent the string class and add a method called ToVoice().

You can download the project here
When you run the method ToVoice() a synthetic voice will say in this case "painkiller" 🙂
A simple example but using extension is easy, notice that the first parameter uses the this keyword to tell the compiler wich target type the method is to be used for.

With Linq came… Part one

What´s the news in C# 3.0? Well the big news is Linq and the evolution of C# that the Linq project forced the C# developer team to implement. This new cool stuff will make C# more powerfull even if you dont use Linq. So what is the new stuff?

Query Expression

It´s so awesome, I remember when I first read about SQL 2005, rumors where saying that you should be enabled to write Stored procedures with the C# language. How disappointed I was when SQL 2005 was released, yes you could write C# and let SQL host the assembly but this was no news realy you could not write real Querys with the power of TSQL. With Query Expression this is possible, it has even more power then TSQL itself take a look at this simple example.

var query = from c in customers
where c.City ==  "Stockholm"
orderby c.ContactName.Split(‘ ‘)[1]
select c;

It is very simple query but notice how easy it is to use a C# string functions to sort on contactname (contact name is first name + last name), it´s just uses the Split and Array functionallity. You could do that in TSQL but not with the help of any .NET language.
This query expression works on any Collection in .NET that implements IEnumerable (and all .NET collection does) and you could of course create your own.
What is var you may ask and how do I use this? To use the simplest way just do like this:

foreach (var item in query)
{
    Console.WriteLine(item.ContactName);
}

It is when you start iterating the query realy fires, not in the select c statement.

C# 3.0 feature: ‘var’ Local Variable Inference

var is a new keyword and when you first se how it works you may think this is something taken from Visual Basic Language who has a Variant datatype. But it´s not (and thats good VB is pure evil) it is strongly typed and it only works in a local scope. Here is an Example:

//C# 3.0 feature: Object and Collection Initializers in a mix

//C# 3.0 feature: ‘var’ Local Variable Inference (strong typed, no object or variant list it is a List<Customer>)
//Local Variable Inference only works on variables in local scope
var list = new List<Customer>
{
    new Customer(){CustomerId =  "FRAERI", City = "Stockholm", ContactName = "Frasse Ericsson"}
    new Customer(){CustomerId =  "BOSAND", City = "Stockholm", ContactName = "Bosse Andersson"}
}

The code also show two other new features Object and Collection Initalizers here mixed all together. The var datatype will be a List<Customer> and even in design time the Intellisense will show that. By inference the compiler will understand what the datatype must be, this is usefull in local scope, you can write more compact code. The C# team have done som more improvements to write less code, more samples to come…