by thebeebs
12. September 2009 06:52
This is a demo where it oddly took me longer to think of an example than it did write an example. You can download the example code at the bottom of the article.
In some cases when you writing a lambda you might want to pass a parameter from one portion of the chain to the next. Sadly it’s not that easy because each section of a lambda chain passes the result of that section but you can’t pass other parameters down to the next section.
Take if you will the example below, I have two sets of data, one set is a list of boys names the other is a list of girls names.
Using a lambda I want to loop through the boys name and the girls names and create all the possible combination of dates that these bachelors and bachelorettes could go on.
The following two blocks creates the two collections that I'll use. The method I use to create the lists is called casting by example, and is a good way to create a list of anonymous objects.
So that I can see the results I'll create a data grid. I’ll give the grid one column which will bind to the property “Date”.
Now for the lambda, firstly I will Order by the boys surnames which is done in line 33
Next I will use .SelectMany on the boys collection (c1) and the first thing I do after the => is select from the girls collection (c2). The cool thing about this is that because the girls collection is nested inside the SelectMany I am able to access both the girls collection and the boys collection at the same time. Therefore on line 35 inside the select I create a new anonymous type and concatenate the properties from the Boys (c1) and Girls (c2) Collections.
The reson I create an anonomous type here is because I can give the property the name “date” which will mean it will bind to the grid I set up at the start of this example.
Finally I bind the results to the first data grid in lines 36 and 37.
The results look something like this:
5f7807d9-6746-4d9e-9813-bb337a81b056|0|.0
Tags: