Månad: januari 2009

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.

Annonser