I'm enjoying life without so many for loops in Orcas. You know, if I want to extract a sample from a list into a fresh list I have to do this at present:
// new up the container
IEnumerable<Employee> newEmployees = new IEnumerable<Employee>();
// loop through each employee
foreach (Employee employee in _allEmployees)
{
// find the new ones
if (employee.StartDate > DateTime.Today.AddMonths(-3))
{
_newEmployees.Add(employee);
}
}
return newEmployees;
Now, using Linq I can focus on *what* I'm doing and just write this
IEnumerable <Employee> newEmployees = from emp in _newEmployees where emp.StartDate > DateTime.Today.AddMonths(-3) select emp;
return newEmployees;
Or, using a Lambda, which seems to be more fashionable (a phenomena I'm calling Linq snobbery):
return _allEmployees.Where(emp => emp.StartDate > DateTime.Today.AddMonths(-3));
Converting lists
Want to convert the list into a different type? How about this...
_newEmployees.Select<Employee, Person>(emp => {
return new Person { Name = emp.Name, Address = emp.Address };
});
Notice how I'm using the new Object Initializers feature to create the person. Whilst this is handy, I still prefer to use a constructor. Fortunately, I don't have to explain why because Bruusi has already done so in this post
Initialisation using constructors.

Post By
Josh Twist
11:55 PM
04 Jun 2007
» Next Post:
The Navman F20 Satellite Navigation Device
« Previous Post:
Small but juicy features coming in Orcas
Comments are closed for this post.
Posted by
James Snape
@
05 Jun 2007
8:44 AM
Don't forget your var's:
var newEmployees = from emp in _newEmployees where emp.StartDate > DateTime.Today.AddMonths(-3) select emp;
Posted by
Granville
@
06 Jun 2007
8:10 AM
He can't get enough of the lambdas now can he?!
F# all the way baby!!!!!!
Posted by
Josh
@
06 Jun 2007
8:26 AM
Granville, you told me I couldn't use lambdas to convert a list! Big dissapointment for me on your penultimate day...
Too much playing with F#!
;)
Posted by
Granville Barnett
@
29 Jun 2007
4:13 AM
I never said that!! Your making me look bad now...take it back!!!
Lambdas are a thing of beauty - but declarative constructs are coming more and more in the future! Jump on board the parallel train now before you get left behind!! => If you have some spare time take a look at PLINQ, Accelerator (Parallel libraries that use GPU from MSR) and F#. You won't regret it!
Oh yeh, and seens as though you are on the inside send the C# team a mail and ask them when they are gonna support inline MSIL a'la C++ with assembly.
Don't hate the player hate the game :-)