<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>Jesper Niedermann's .NET Blog - Linq</title>
    <link>http://www.niedermann.dk/</link>
    <description>about .NET and related technologies</description>
    <language>en-us</language>
    <copyright>Jesper Niedermann</copyright>
    <lastBuildDate>Fri, 01 May 2009 20:12:40 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.2.8279.16125</generator>
    <managingEditor>jesper@niedermann.dk</managingEditor>
    <webMaster>jesper@niedermann.dk</webMaster>
    <item>
      <trackback:ping>http://www.niedermann.dk/Trackback.aspx?guid=ca551b37-7872-4ea6-9db9-f3c400cc3854</trackback:ping>
      <pingback:server>http://www.niedermann.dk/pingback.aspx</pingback:server>
      <pingback:target>http://www.niedermann.dk/PermaLink,guid,ca551b37-7872-4ea6-9db9-f3c400cc3854.aspx</pingback:target>
      <dc:creator>Jesper Niedermann</dc:creator>
      <wfw:comment>http://www.niedermann.dk/CommentView,guid,ca551b37-7872-4ea6-9db9-f3c400cc3854.aspx</wfw:comment>
      <wfw:commentRss>http://www.niedermann.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=ca551b37-7872-4ea6-9db9-f3c400cc3854</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
If you want to Execute something on each element of the result of a Linq expression.
You can either loop over the result using foreach(...) or turn the result into a List
using .ToList(), and then use .Foreach(...) on the resulting list. Like this:
</p>
        <pre class="c#" name="code">(from excep in ErrorList<br />
where excep is ArgumentException select excep)<br />
.ToList().ForEach(e =&gt; Console.WriteLine(e.Message));</pre>
        <p>
This is ugly, and I prefer to make my own Extension method for IEnumerable&lt;T&gt;
called Execute(...):
</p>
        <pre class="c#" name="code">public static void Execute&lt;T&gt;(this IEnumerable&lt;T&gt; list, Action&lt;T&gt; action)<br />
{<br />
foreach(T element in list)<br />
{<br />
action(element);<br />
}<br />
}</pre>
        <p>
This means you can do this instead:
</p>
        <pre class="c#" name="code">(from excep in ErrorList<br />
where excep is ArgumentException select excep)<br />
.Execute(e =&gt; Console.WriteLine(e.Message));</pre>
        <p>
Back in the days when I used Linq in a program for the first time, I wondered why
there was no way to execute an action on each element of a list, so I implemented
the Execute method. 
</p>
        <p>
It was only later that I discovered that the default way was .ToList().Foreach(...) 
</p>
        <p>
I must say I still prefer my original approach.
</p>
        <p>
BTW: In a small none scientific test I have tested the two approaches. 
</p>
        <p>
With Linq To Objects iterating over 100000 integers and printing them to the Console
takes about 21 seconds with the Foreach method and about 20 seconds with the Execute
method, so it is even faster at least for this particular example. Though nothing
to get excited about. :O) 
</p>
        <p>
The test was done in a Vista VPC with VS2008, 
</p>
        <div class="wlWriterSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:11f4e80d-be65-4afd-81f7-669eb0b45764" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
          <p>
Small performance test: <a href="http://www.niedermann.dk/content/binary/WindowsLiveWriter/ExecuteMethodforLinq_1420F/LinqPerfTest.zip" target="_blank">LinqPerfTest.zip</a></p>
        </div>
        <img width="0" height="0" src="http://www.niedermann.dk/aggbug.ashx?id=ca551b37-7872-4ea6-9db9-f3c400cc3854" />
      </body>
      <title>Execute Method for Linq</title>
      <guid isPermaLink="false">http://www.niedermann.dk/PermaLink,guid,ca551b37-7872-4ea6-9db9-f3c400cc3854.aspx</guid>
      <link>http://www.niedermann.dk/2009/05/01/ExecuteMethodForLinq.aspx</link>
      <pubDate>Fri, 01 May 2009 20:12:40 GMT</pubDate>
      <description>&lt;p&gt;
If you want to Execute something on each element of the result of a Linq expression.
You can either loop over the result using foreach(...) or turn the result into a List
using .ToList(), and then use .Foreach(...) on the resulting list. Like this:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;(from excep in ErrorList&lt;br&gt;
where excep is ArgumentException select excep)&lt;br&gt;
.ToList().ForEach(e =&amp;gt; Console.WriteLine(e.Message));&lt;/pre&gt;
&lt;p&gt;
This is ugly, and I prefer to make my own Extension method for IEnumerable&amp;lt;T&amp;gt;
called Execute(...):
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;public static void Execute&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; list, Action&amp;lt;T&amp;gt; action)&lt;br&gt;
{&lt;br&gt;
foreach(T element in list)&lt;br&gt;
{&lt;br&gt;
action(element);&lt;br&gt;
}&lt;br&gt;
}&lt;/pre&gt;
&lt;p&gt;
This means you can do this instead:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;(from excep in ErrorList&lt;br&gt;
where excep is ArgumentException select excep)&lt;br&gt;
.Execute(e =&amp;gt; Console.WriteLine(e.Message));&lt;/pre&gt;
&lt;p&gt;
Back in the days when I used Linq in a program for the first time, I wondered why
there was no way to execute an action on each element of a list, so I implemented
the Execute method. 
&lt;/p&gt;
&lt;p&gt;
It was only later that I discovered that the default way was .ToList().Foreach(...) 
&lt;/p&gt;
&lt;p&gt;
I must say I still prefer my original approach.
&lt;/p&gt;
&lt;p&gt;
BTW: In a small none scientific test I have tested the two approaches. 
&lt;/p&gt;
&lt;p&gt;
With Linq To Objects iterating over 100000 integers and printing them to the Console
takes about 21 seconds with the Foreach method and about 20 seconds with the Execute
method, so it is even faster at least for this particular example. Though nothing
to get excited about. :O) 
&lt;/p&gt;
&lt;p&gt;
The test was done in a Vista VPC with VS2008, 
&lt;/p&gt;
&lt;div class="wlWriterSmartContent" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:11f4e80d-be65-4afd-81f7-669eb0b45764" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"&gt;
&lt;p&gt;
Small performance test: &lt;a href="http://www.niedermann.dk/content/binary/WindowsLiveWriter/ExecuteMethodforLinq_1420F/LinqPerfTest.zip" target="_blank"&gt;LinqPerfTest.zip&lt;/a&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.niedermann.dk/aggbug.ashx?id=ca551b37-7872-4ea6-9db9-f3c400cc3854" /&gt;</description>
      <comments>http://www.niedermann.dk/CommentView,guid,ca551b37-7872-4ea6-9db9-f3c400cc3854.aspx</comments>
      <category>.NET</category>
      <category>Linq</category>
      <category>Tips &amp; Tricks</category>
    </item>
    <item>
      <trackback:ping>http://www.niedermann.dk/Trackback.aspx?guid=05924408-b429-4095-8111-90fec2ba338b</trackback:ping>
      <pingback:server>http://www.niedermann.dk/pingback.aspx</pingback:server>
      <pingback:target>http://www.niedermann.dk/PermaLink,guid,05924408-b429-4095-8111-90fec2ba338b.aspx</pingback:target>
      <dc:creator>Jesper Niedermann</dc:creator>
      <wfw:comment>http://www.niedermann.dk/CommentView,guid,05924408-b429-4095-8111-90fec2ba338b.aspx</wfw:comment>
      <wfw:commentRss>http://www.niedermann.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=05924408-b429-4095-8111-90fec2ba338b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
What is Linq ? You probably think you know the answer, Linq is after all already quite
dated. Well in my experience chances are you only know part of the story. Most of
the people I have met have a slight misconception of Linq which limits their use of
this great technology. 
</p>
        <p>
Let me explain. Linq of course means "Language Integrated Query", we all knew that.
This basically refers to the syntactic sugar that Microsoft has poured over the C#3.0
language. I.e the from, where and select keywords and a few more.
</p>
        <p>
In practice Linq is more. It is also a set of Extension methods in a given Linq provider,
and a new way of coding, and furthermore many of the C#3.0 features are there to make
Linq more useful. Like the var keyword, and lambda expressions.
</p>
        <p>
What I think is limiting the use of Linq is that most people think Linq is a database
technology. It is true that Linq can be used for querying databases if you use a Linq
provider for a database technology like The LinqToEntities, LinqToSQL or Linq to some
other ORM. This is basically Microsoft's "fault", Linq can be used for querying databases,
and that is how Linq was promoted, I guess because of the ORM hype.
</p>
        <p>
I was so fortunate to talk to one of the creators of Linq, Anders Hejlsberg in October
2008 when he was giving a lecture in Hilleroed, Denmark. I presented my view to him,
that I thought it was a pity that Linq was viewed only as a database technology. He
agreed with me, and said that this was because database access was the driving force
behind Linq to begin with, and for marketing reasons. 
</p>
        <p>
But what is Linq really then ? If you look at an old fashioned SQL query 
</p>
        <pre class="sql" name="code">SELECT SomeColumn FROM SomeTable</pre>
        <p>
You query relational data (SomeTable), and in return you get relational data (A set
containing SomeColumn). With Linq you have much more power. You can query anything
that implements the IEnumerable&lt;XXX&gt; interface, and you can return one or more
.NET objects of any type.
</p>
        <p>
So therefore I think it is much more productive to look at Linq as a means to transform
data. In some ways Linq can replace XSLT, I am no XSLT expert but I would guess that
you can always write a Linq expression to replace any XSLT transformation, as long
as you work in a .NET assembly. Of course an XML document can refer directly to an
XSLT transformation, which is not possible with Linq.
</p>
        <p>
Transformations of data are so common in a computer program that we don't even notice
them. In fact we use them all the time. And consequently we can use Linq expressions
all the time, and should use them most of the time. I would argue that a Linq expression
is more readable than "normal" code most of the time. If it is less readable or performs
badly you might choose another option.
</p>
        <p>
Here are a few examples of transformations that we don't think of as transformations:
</p>
        <ul>
          <li>
Outputting errors to a logfile, or the console, or an eventlog. In this case exceptions
are transformed to lines of text. 
</li>
          <li>
Building a dynamic menu from data in an XML file. In this case the data in the XML
file is transformed into menuitems. 
</li>
          <li>
Building a dynamic Xaml page from some input. The input data is transformed into Xaml.</li>
        </ul>
        <p>
I will know give you some concrete codefragments to show these types of queries.
</p>
        <h3>Outputting errors
</h3>
        <p>
Let's say that you have collected error information in the form of a List of Exceptions.
Assume in the following code that ErrorList is a List&lt;Exception&gt;:
</p>
        <pre class="c#" name="code">(from excep in ErrorList 
<br />
where excep is ArgumentException<br />
select excep).ToList()<br />
.ForEach(e =&gt; Console.WriteLine(e.Message));</pre>
        <p>
Now you have transformed your Exception data to Visual Data in the Console. In this
example only ArgumentException's are printed. Of course you could easily print something
better than just the message, e.g ToString() or perhaps a PrettyPrint() extension
method for Exception that digs all InnerExceptions out, and prints everything in a
nice readable format.
</p>
        <h3>Building a dynamic menu
</h3>
        <p>
This example is from my <a href="http://wiicursor.codeplex.com">WiiCursor</a> project:
</p>
        <pre class="c#" name="code">m_ConfigurationMenu = new MenuItem("Configure");<br />
var confMenus = 
<br />
from configuration in configurations<br />
select Util.GetMenuItem(<br />
configuration.Name, 
<br />
(sender, args) =&gt; Configure((MenuItem)sender, configuration), 
<br />
configuration.Default);<br />
m_ConfigurationMenu.MenuItems.AddRange(confMenus.ToArray());</pre>
        <p>
In the code shown 'configurations' is a List&lt;WCConfiguration&gt; where WCConfiguration
is a class that corresponds to an XML file, and gets initialized by the file. The
GetMenuItem(...) method basically "news up" the MenuItem and connects a click eventhandler
to it by passing the lambda expression '(sender, args) =&gt; Configure((MenuItem)sender,
configuration)' to the MenuItems constructor.
</p>
        <p>
So when the user clicks the MenuItem what happens is that the Configure(...) method
is called with the MenuItem and most importantly the correct WCConfiguration as parameters.
</p>
        <p>
This might not be the most readable code in the universe. In fact I violate one of
my own best practices. Only use the var keyword if the resulting type, here MenuItem,
is readable in another way. In the original version I called new MenuItem(...) directly,
so that is my (admittedly bad) excuse.
</p>
        <p>
But still the code beautifully illustrates how a Linq expression can Transform the
context of XML files to MenuItems that act upon the information in the corresponding
file.
</p>
        <h3>Building a dynamic Xaml page
</h3>
        <p>
In another project of mine, not yet published, I experiment with logging mouse moves
to help me register the time I have used on different projects at the end of the week.
A common task for employees around the world. I log the mousemoves in an XML file
using a custom format.
</p>
        <pre class="xml" name="code">&lt;?xml version="1.0" encoding="utf-8"?&gt;<br />
&lt;Activities&gt;<br />
&lt;Activity Name="Activity" Start="10-03-2009 08:01:42" End="10-03-2009 10:01:54"
/&gt;<br />
&lt;Activity Name="Activity" Start="10-03-2009 12:00:00" End="10-03-2009 16:01:05"
/&gt;<br />
&lt;/Activities&gt;</pre>
        <p>
To make it more appealing visually I transform it to a Xaml file that I load dynamically
in a WPF project. The smart thing is that I can do it in a VB.NET assembly combining
XML Literals and LinqToXML. Below is the first few lines of the Transformer class
that contains the methods to create the Xaml file. Notice how the Xaml can be inlined
easily in VB.NET since it is also XML. 
</p>
        <p>
Imports System.Linq<br />
Imports System.Linq.Enumerable<br />
Imports System.Xml.Linq<br />
Imports &lt;xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&gt;<br />
Imports &lt;xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;<br /><br />
Public Class Transformer<br /><br />
    Private Const Column0Width As Integer = 50<br />
    Private Const Column1Width As Integer = 50<br />
    Private Const Column2Width As Integer = 70<br />
    Private Const Column3Width As Integer = 170<br />
    Private Const Column4Width As Integer = 40<br /><br />
    'Converts from a basic XDocument with Activities to a rich one
using Xaml.<br />
    'This is done with VB.NET because of the rich LinqToXML experience
in VB.<br />
    Public Shared Function ConvertToXaml(ByVal convertFrom As XDocument)
As XDocument<br /><br />
        Dim months As Integer() = {1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12}<br /><br /><br />
        Dim doc As XDocument = New XDocument( _<br />
&lt;Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"<br />
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"<br />
    Title="Time Statistics" Height="302" Width="514"&gt;<br />
    &lt;Grid&gt;<br />
        &lt;TabControl Name="ActivitiesTabControl"&gt;<br />
            &lt;%= From month
In months _<br />
               
Select _<br />
               
&lt;TabItem Header=&lt;%= NameOfMonth(month) %&gt; Height="20" Width="80" Selector.IsSelected=&lt;%=
SelectMonth(month) %&gt;&gt;<br />
                   
&lt;ScrollViewer VerticalScrollBarVisibility="Auto"&gt;<br />
                       
&lt;Grid&gt;<br />
                           
&lt;%= ColumnDefinitions() %&gt;<br />
                           
&lt;%= RowDefinitions(NumberOfRows(month, convertFrom)) %&gt;<br />
                           
&lt;%= RowHeaders() %&gt;<br />
                           
&lt;%= RowsOfMonth(month, convertFrom) %&gt;<br />
                       
&lt;/Grid&gt;<br />
                   
&lt;/ScrollViewer&gt;<br />
               
&lt;/TabItem&gt; %&gt;<br />
        &lt;/TabControl&gt;<br />
    &lt;/Grid&gt;<br />
&lt;/Window&gt; _<br />
               
)<br />
        Return doc<br />
    End Function<br />
    ...
</p>
        <p>
XML Literals is the only reason why I sometimes use VB.NET, otherwise I am a C# guy.
I would have loved C# to have this nice feature too, my guess is that it was impossible
because angel brackets '&lt;' are reserved for generics in C#. 
</p>
        <p>
Apart from giving an appealing visual look the code also makes calculations like summing
up the time used in an entire day. Linq is ideal for this too.
</p>
        <h3>Summing up
</h3>
        <p>
I hope I have convinced you that Linq is more than just a database technology. You
knew it already of course, but did you live it and breathe it :O) In my opinion Linq
is such an integral part of C#3.0 that there is no avoiding using it all the time.
</p>
        <img width="0" height="0" src="http://www.niedermann.dk/aggbug.ashx?id=05924408-b429-4095-8111-90fec2ba338b" />
      </body>
      <title>The Missing Linq / What is Linq really ?</title>
      <guid isPermaLink="false">http://www.niedermann.dk/PermaLink,guid,05924408-b429-4095-8111-90fec2ba338b.aspx</guid>
      <link>http://www.niedermann.dk/2009/03/18/TheMissingLinqWhatIsLinqReally.aspx</link>
      <pubDate>Wed, 18 Mar 2009 21:49:20 GMT</pubDate>
      <description>&lt;p&gt;
What is Linq ? You probably think you know the answer, Linq is after all already quite
dated. Well in my experience chances are you only know part of the story. Most of
the people I have met have a slight misconception of Linq which limits their use of
this great technology. 
&lt;/p&gt;
&lt;p&gt;
Let me explain. Linq of course means "Language Integrated Query", we all knew that.
This basically refers to the syntactic sugar that Microsoft has poured over the C#3.0
language. I.e the from, where and select keywords and a few more.
&lt;/p&gt;
&lt;p&gt;
In practice Linq is more. It is also a set of Extension methods in a given Linq provider,
and a new way of coding, and furthermore many of the C#3.0 features are there to make
Linq more useful. Like the var keyword, and lambda expressions.
&lt;/p&gt;
&lt;p&gt;
What I think is limiting the use of Linq is that most people think Linq is a database
technology. It is true that Linq can be used for querying databases if you use a Linq
provider for a database technology like The LinqToEntities, LinqToSQL or Linq to some
other ORM. This is basically Microsoft's "fault", Linq can be used for querying databases,
and that is how Linq was promoted, I guess because of the ORM hype.
&lt;/p&gt;
&lt;p&gt;
I was so fortunate to talk to one of the creators of Linq, Anders Hejlsberg in October
2008 when he was giving a lecture in Hilleroed, Denmark. I presented my view to him,
that I thought it was a pity that Linq was viewed only as a database technology. He
agreed with me, and said that this was because database access was the driving force
behind Linq to begin with, and for marketing reasons. 
&lt;/p&gt;
&lt;p&gt;
But what is Linq really then ? If you look at an old fashioned SQL query 
&lt;/p&gt;
&lt;pre class="sql" name="code"&gt;SELECT SomeColumn FROM SomeTable&lt;/pre&gt;
&lt;p&gt;
You query relational data (SomeTable), and in return you get relational data (A set
containing SomeColumn). With Linq you have much more power. You can query anything
that implements the IEnumerable&amp;lt;XXX&amp;gt; interface, and you can return one or more
.NET objects of any type.
&lt;/p&gt;
&lt;p&gt;
So therefore I think it is much more productive to look at Linq as a means to transform
data. In some ways Linq can replace XSLT, I am no XSLT expert but I would guess that
you can always write a Linq expression to replace any XSLT transformation, as long
as you work in a .NET assembly. Of course an XML document can refer directly to an
XSLT transformation, which is not possible with Linq.
&lt;/p&gt;
&lt;p&gt;
Transformations of data are so common in a computer program that we don't even notice
them. In fact we use them all the time. And consequently we can use Linq expressions
all the time, and should use them most of the time. I would argue that a Linq expression
is more readable than "normal" code most of the time. If it is less readable or performs
badly you might choose another option.
&lt;/p&gt;
&lt;p&gt;
Here are a few examples of transformations that we don't think of as transformations:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Outputting errors to a logfile, or the console, or an eventlog. In this case exceptions
are transformed to lines of text. 
&lt;li&gt;
Building a dynamic menu from data in an XML file. In this case the data in the XML
file is transformed into menuitems. 
&lt;li&gt;
Building a dynamic Xaml page from some input. The input data is transformed into Xaml.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I will know give you some concrete codefragments to show these types of queries.
&lt;/p&gt;
&lt;h3&gt;Outputting errors
&lt;/h3&gt;
&lt;p&gt;
Let's say that you have collected error information in the form of a List of Exceptions.
Assume in the following code that ErrorList is a List&amp;lt;Exception&amp;gt;:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;(from excep in ErrorList 
&lt;br&gt;
where excep is ArgumentException&lt;br&gt;
select excep).ToList()&lt;br&gt;
.ForEach(e =&amp;gt; Console.WriteLine(e.Message));&lt;/pre&gt;
&lt;p&gt;
Now you have transformed your Exception data to Visual Data in the Console. In this
example only ArgumentException's are printed. Of course you could easily print something
better than just the message, e.g ToString() or perhaps a PrettyPrint() extension
method for Exception that digs all InnerExceptions out, and prints everything in a
nice readable format.
&lt;/p&gt;
&lt;h3&gt;Building a dynamic menu
&lt;/h3&gt;
&lt;p&gt;
This example is from my &lt;a href="http://wiicursor.codeplex.com"&gt;WiiCursor&lt;/a&gt; project:
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;m_ConfigurationMenu = new MenuItem("Configure");&lt;br&gt;
var confMenus = 
&lt;br&gt;
from configuration in configurations&lt;br&gt;
select Util.GetMenuItem(&lt;br&gt;
configuration.Name, 
&lt;br&gt;
(sender, args) =&amp;gt; Configure((MenuItem)sender, configuration), 
&lt;br&gt;
configuration.Default);&lt;br&gt;
m_ConfigurationMenu.MenuItems.AddRange(confMenus.ToArray());&lt;/pre&gt;
&lt;p&gt;
In the code shown 'configurations' is a List&amp;lt;WCConfiguration&amp;gt; where WCConfiguration
is a class that corresponds to an XML file, and gets initialized by the file. The
GetMenuItem(...) method basically "news up" the MenuItem and connects a click eventhandler
to it by passing the lambda expression '(sender, args) =&amp;gt; Configure((MenuItem)sender,
configuration)' to the MenuItems constructor.
&lt;/p&gt;
&lt;p&gt;
So when the user clicks the MenuItem what happens is that the Configure(...) method
is called with the MenuItem and most importantly the correct WCConfiguration as parameters.
&lt;/p&gt;
&lt;p&gt;
This might not be the most readable code in the universe. In fact I violate one of
my own best practices. Only use the var keyword if the resulting type, here MenuItem,
is readable in another way. In the original version I called new MenuItem(...) directly,
so that is my (admittedly bad) excuse.
&lt;/p&gt;
&lt;p&gt;
But still the code beautifully illustrates how a Linq expression can Transform the
context of XML files to MenuItems that act upon the information in the corresponding
file.
&lt;/p&gt;
&lt;h3&gt;Building a dynamic Xaml page
&lt;/h3&gt;
&lt;p&gt;
In another project of mine, not yet published, I experiment with logging mouse moves
to help me register the time I have used on different projects at the end of the week.
A common task for employees around the world. I log the mousemoves in an XML file
using a custom format.
&lt;/p&gt;
&lt;pre class="xml" name="code"&gt;&amp;lt;?xml version="1.0" encoding="utf-8"?&amp;gt;&lt;br&gt;
&amp;lt;Activities&amp;gt;&lt;br&gt;
&amp;lt;Activity Name="Activity" Start="10-03-2009 08:01:42" End="10-03-2009 10:01:54"
/&amp;gt;&lt;br&gt;
&amp;lt;Activity Name="Activity" Start="10-03-2009 12:00:00" End="10-03-2009 16:01:05"
/&amp;gt;&lt;br&gt;
&amp;lt;/Activities&amp;gt;&lt;/pre&gt;
&lt;p&gt;
To make it more appealing visually I transform it to a Xaml file that I load dynamically
in a WPF project. The smart thing is that I can do it in a VB.NET assembly combining
XML Literals and LinqToXML. Below is the first few lines of the Transformer class
that contains the methods to create the Xaml file. Notice how the Xaml can be inlined
easily in VB.NET since it is also XML. 
&lt;/p&gt;
&lt;p&gt;
Imports System.Linq&lt;br&gt;
Imports System.Linq.Enumerable&lt;br&gt;
Imports System.Xml.Linq&lt;br&gt;
Imports &amp;lt;xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&amp;gt;&lt;br&gt;
Imports &amp;lt;xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&amp;gt;&lt;br&gt;
&lt;br&gt;
Public Class Transformer&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Private Const Column0Width As Integer = 50&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Private Const Column1Width As Integer = 50&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Private Const Column2Width As Integer = 70&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Private Const Column3Width As Integer = 170&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Private Const Column4Width As Integer = 40&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; 'Converts from a basic XDocument with Activities to a rich one
using Xaml.&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; 'This is done with VB.NET because of the rich LinqToXML experience
in VB.&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Public Shared Function ConvertToXaml(ByVal convertFrom As XDocument)
As XDocument&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Dim months As Integer() = {1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12}&lt;br&gt;
&lt;br&gt;
&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Dim doc As XDocument = New XDocument( _&lt;br&gt;
&amp;lt;Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; Title="Time Statistics" Height="302" Width="514"&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;Grid&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;TabControl Name="ActivitiesTabControl"&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;%= From month
In months _&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
Select _&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;TabItem Header=&amp;lt;%= NameOfMonth(month) %&amp;gt; Height="20" Width="80" Selector.IsSelected=&amp;lt;%=
SelectMonth(month) %&amp;gt;&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;ScrollViewer VerticalScrollBarVisibility="Auto"&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;Grid&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;%= ColumnDefinitions() %&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;%= RowDefinitions(NumberOfRows(month, convertFrom)) %&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;%= RowHeaders() %&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;%= RowsOfMonth(month, convertFrom) %&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;/Grid&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;/ScrollViewer&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
&amp;lt;/TabItem&amp;gt; %&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/TabControl&amp;gt;&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/Grid&amp;gt;&lt;br&gt;
&amp;lt;/Window&amp;gt; _&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
)&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Return doc&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; End Function&lt;br&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; ...
&lt;/p&gt;
&lt;p&gt;
XML Literals is the only reason why I sometimes use VB.NET, otherwise I am a C# guy.
I would have loved C# to have this nice feature too, my guess is that it was impossible
because angel brackets '&amp;lt;' are reserved for generics in C#. 
&lt;/p&gt;
&lt;p&gt;
Apart from giving an appealing visual look the code also makes calculations like summing
up the time used in an entire day. Linq is ideal for this too.
&lt;/p&gt;
&lt;h3&gt;Summing up
&lt;/h3&gt;
&lt;p&gt;
I hope I have convinced you that Linq is more than just a database technology. You
knew it already of course, but did you live it and breathe it :O) In my opinion Linq
is such an integral part of C#3.0 that there is no avoiding using it all the time.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.niedermann.dk/aggbug.ashx?id=05924408-b429-4095-8111-90fec2ba338b" /&gt;</description>
      <comments>http://www.niedermann.dk/CommentView,guid,05924408-b429-4095-8111-90fec2ba338b.aspx</comments>
      <category>.NET</category>
      <category>Linq</category>
    </item>
  </channel>
</rss>