<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>FormatException &#187; Reflection</title>
	<atom:link href="http://www.formatexception.com/tag/reflection/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.formatexception.com</link>
	<description>Ramblings on developing in the Windows World</description>
	<lastBuildDate>Mon, 24 May 2010 15:43:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Tiptoe Through the Tulips &#8230; LINQeses&#8230;es</title>
		<link>http://www.formatexception.com/2008/09/tiptoe-through-the-tulips-linqeseses/</link>
		<comments>http://www.formatexception.com/2008/09/tiptoe-through-the-tulips-linqeseses/#comments</comments>
		<pubDate>Wed, 17 Sep 2008 15:30:20 +0000</pubDate>
		<dc:creator>Brian</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[generics]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://www.formatexception.com/?p=50</guid>
		<description><![CDATA[ As most can attest when launching into the world of WPF you have to jump in and hope you can figure out how to swim before you drown.  It has a huge learning curve but the end results are usually pretty amazing.
LINQ, on the other hand, you can slowly dip a toe in, see how tepid [...]]]></description>
			<content:encoded><![CDATA[<p><!--StartFragment --> As most can attest when launching into the world of WPF you have to jump in and hope you can figure out how to swim before you drown.  It has a huge learning curve but the end results are usually pretty amazing.</p>
<p>LINQ, on the other hand, you can slowly dip a toe in, see how tepid the water is, and then slowly immerse your whole body sliding into the warm 98 degree water.  Over the course of 7 months now I have been slowing dipping into the water called LINQ and wanted to give you a few examples where I found it particularly useful.  Unlike a cruel father I will not throw you into the water and hope you can swim but want to slowly lead you into the fold.</p>
<p>So what the hell is LINQ?  Well, it stands for Language INtegrated Query.  It is a way to query lists in code.  Really that&#8217;s it.  You&#8217;re f-in me Brian, aren&#8217;t you?  Yes, yes I am.  That is the fundamental idea behind LINQ but it can do so much more.</p>
<p>I suppose I should start with the var keyword.  You VB fans will cheer at this.  var is a variable declaration where the type of the variable is implicit in the constructor of the item being created.  This is similar to the Dim except that we are still statically typed here.  In .Net 3.5 the var keyword can be used anywhere you are defining a variable that the type can be implied.</p>
<p>Good Examples:</p>
<div style="background-color: #FFF;">
<tt><span style="color: #3333ff;">var</span> myInt = 3;<br />
<span style="color: #3333ff;">var</span> myDouble = 2.2;<br />
<span style="color: #3333ff;">var</span> files = new <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">FileInfo</span>&gt;();</tt></div>
<p><br/></p>
<p>Bad Examples:</p>
<div style="background-color: #FFF;">
<tt><span style="color: #3333ff;">var</span> myDouble = 3;<span style="color: #33cc00;">//not a double and myDouble will actually be an int</span><br />
<span style="color: #3333ff;">var</span> myString = <span style="color: #3333ff;">null</span>;<span style="color: #33cc00;">//type cannot be implied, will result in compile error</span></tt></div>
<p><br/></p>
<p>The easiest use for LINQ is in sorting.  No more needing to define an IComparable, just define your sort in an orderby clause.  LINQ has some similarities to writing SQL except that in order to facilitate compilation and intelli-sense the order of the query is a bit different.</p>
<p>Take this code for example:</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">var</span> files = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">FileInfo</span>&gt;();<br />
<span style="color: #3333ff;">var</span> ArchiveDirectory = <span style="color: #990000;">"C:\Archive"</span>;<br />
<span style="color: #3333ff;">var</span> archivedFiles = <span style="color: #00cccc;">Directory</span>.GetFiles(ArchiveDirectory);<span style="color: #33cc00;">//will be of type string []</span><br />
<span style="color: #3333ff;">foreach</span> (<span style="color: #3333ff;">var</span> filePath <span style="color: #3333ff;">in</span> archivedFiles)<br />
{<br />
    <span style="color: #3333ff;">var</span> fi = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">FileInfo</span>(filePath);<br />
    files.Add(fi);<br />
}<br />
<span style="color: #33cc00;">//now sort the file list based on last write time</span><br />
<span style="color: #3333ff;">var</span> sortedFiles = <span style="color: #3333ff;">from </span>file <span style="color: #3333ff;">in </span>files <span style="color: #3333ff;">orderby </span>file.LastWriteTime <span style="color: #3333ff;">descending select</span> file;<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>Now, up until that last line it is standard C#.  The last line appears to be some sort of odd jacked-up sql.  If we break it down, however, you will see the power.</p>
<div style="background-color: #FFF;"><tt><span style="color: #3333ff;">from </span>file <span style="color: #3333ff;">in </span>files</tt></div>
<p>basically for each file in our files list</p>
<div style="background-color: #FFF;"><tt><span style="color: #3333ff;">orderby </span>file.LastWriteTime</tt></div>
<p>LastWriteTime is a property on FileInfo.  files is a list of FileInfo, therefore each file is a FileInfo object.  Intelli-sense is fully supported here so when you type in file and put the dot it shows you all the properties on file as if it were a standardly declared FileInfo.</p>
<div style="background-color: #FFF;"><span style="color: #3333ff;"><tt>descending</tt></span></div>
<p>Like a standard DESC to an orderby clause.  Like sql it implicitly orders by ASC so if you want descending you have to add it.</p>
<div style="background-color: #FFF;"><tt><span style="color: #3333ff;">select </span>file</tt></div>
<p>return the file that applies to the orderby clause.  The may seem a bit redundant and I would agree but it is still needed.</p>
<p>See?  Pretty simple.  No need to write an IComparable just order the list by the LastWriteTime.</p>
<p>So let&#8217;s take this a step further.</p>
<p>I have an example where I have three different tables all of which have the property &#8220;Name&#8221;.  I need to populate three different combo boxes with the values from each of the different tables.  Now I could write a whole bunch of code to do each table values and combo boxes separately but, well, nah!</p>
<p>Here we&#8217;re going to go a bit extreme.  Use a bit of LINQ, throw in some Generics and finally whip it all together with some Reflection.</p>
<p>Start with getting each list and ordering it by name</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">var </span>sortedTypes = <span style="color: #3333ff;">from </span>type <span style="color: #3333ff;">in new </span><span style="color: #00cccc;">TypeService</span>().GetAll() <span style="color: #3333ff;">orderby </span>type.Name <span style="color: #3333ff;">select </span>type;<br />
<span style="color: #3333ff;">var </span>sortedFreqs = <span style="color: #3333ff;">from </span>freq <span style="color: #3333ff;">in new</span> <span style="color: #00cccc;">FrequencyService</span>().GetAll() <span style="color: #3333ff;">orderby </span>freq.Name <span style="color: #3333ff;">select </span>freq;<br />
<span style="color: #3333ff;">var </span>sortedEvents = <span style="color: #3333ff;">from </span>event <span style="color: #3333ff;">in new </span><span style="color: #00cccc;">EventService</span>().GetAll() <span style="color: #3333ff;">orderby </span>event.Name <span style="color: #3333ff;">select </span>event;<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>Well, that should be pretty straight forward now.  We can see the GetAll method of each service returns all the values from a table in the form of a list.  The we use the orderby clause in LINQ to sort it for us by the name.</p>
<p>Now let&#8217;s populate the combo boxes in the form:</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
PopulateComboBox&lt;<span style="color: #00cccc;">Type</span>&gt;(sortedTypes, cboType);<br />
PopulateComboBox&lt;<span style="color: #00cccc;">Frequency</span>&gt;(sortedFreqs, cboFrequency);<br />
PopulateComboBox&lt;<span style="color: #00cccc;">Event</span>&gt;(sortedEvents, cboEvent);<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>And thats all there is.  Pretty simple, huh?<br />
Oh, you want to see what the hell PopulateComboBox does.  Fine, be that way.</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">private void </span>PopulateComboBox&lt;T&gt;(System.Linq.<span style="color: #00cccc;">IOrderedEnumerable</span>&lt;T&gt; List, <span style="color: #00cccc;">ComboBox </span>Box)<br />
{<br />
    <span style="color: #3333ff;">foreach </span>(T val <span style="color: #3333ff;">in </span>List)<br />
    {<br />
        <span style="color: #00cccc;">ComboBoxItem </span>cbi = new <span style="color: #00cccc;">ComboBoxItem</span><br />
            {<br />
                Content = FindReflectedProperty(val, <span style="color: #990000;">"Name"</span>),<br />
                Tag = val<br />
            };<br />
        Box.Items.Add(cbi);<br />
    }<br />
}<br />
<span style="color: #33cc00;">//END CODE</span></tt><span style="color: #33cc00;"><br />
</span></div>
<p><br/><br />
As you can see we can&#8217;t take a var on the first value of the parameter since it&#8217;s type cannot be inferred.  As it would happen using the orderby clause in a LINQ query returns a list with the interface System.Linq.IOrderedEnumerable.  We use the good ole&#8217; generics typeparam when calling the method so at runtime the code knows the type of T.  Additionally you can see that when creating the ComboBoxItem we use the new feature in 3.5 of setting properties on the objects when creating the object (really this happens right after the constructor is called).  The final bit to this is FindReflectedProperty.</p>
<div style="background-color: #FFF;"><tt><span style="color: #33cc00;">//START CODE</span><br />
<span style="color: #3333ff;">public static object </span>FindReflectedProperty(<span style="color: #3333ff;">object </span>Instance, <span style="color: #3333ff;">string </span>PropName)<br />
{<br />
    <span style="color: #3333ff;">if </span>(Instance == <span style="color: #3333ff;">null</span>)<br />
        <span style="color: #3333ff;">return null</span>;<br />
    <span style="color: #3333ff;">foreach </span>(<span style="color: #00cccc;">PropertyInfo </span>pi <span style="color: #3333ff;">in </span>Instance.GetType().GetProperties())<br />
    {<br />
        <span style="color: #3333ff;">if </span>(pi.Name == PropName)<br />
            <span style="color: #3333ff;">return </span>pi.GetValue(Instance, <span style="color: #3333ff;">null</span>);<br />
    }<br />
    <span style="color: #3333ff;">return null</span>;<br />
}<br />
<span style="color: #33cc00;">//END CODE</span></tt></div>
<p><br/></p>
<p>Getting the PropertyInfo on the instance passed in we are able to get the value of the property based on the property name.  Of course we can turn this method into more LINQ but I&#8217;ll leave that to the next in the series where we&#8217;ll dip our whole foot in, which should excite all you foot appreciators (or fetishes or whatever).  If you want to read ahead google LINQ Lambda.</p>
<p>And now your toe is wet, assuming you got this far.</p>
<p>Later &#8216;yall,<br />
Brian</p>



Share and Enjoy:


	<a rel="nofollow"  target="_blank" href="http://digg.com/submit?phase=2&amp;url=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;title=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es&amp;bodytext=%C2%A0As%C2%A0most%20can%20attest%20when%20launching%20into%20the%20world%20of%20WPF%20you%20have%20to%20jump%20in%20and%20hope%20you%20can%20figure%20out%20how%20to%20swim%20before%20you%20drown.%C2%A0%20It%20has%20a%20huge%20learning%20curve%20but%20the%20end%20results%20are%20usually%20pretty%20amazing.%0D%0A%0D%0ALINQ%2C%20on%20the%20other%20hand%2C%20you%20ca" title="Digg"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/digg.png" title="Digg" alt="Digg" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.facebook.com/share.php?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;t=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es" title="Facebook"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/facebook.png" title="Facebook" alt="Facebook" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.dotnetkicks.com/kick/?url=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;title=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es" title="DotNetKicks"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/dotnetkicks.png" title="DotNetKicks" alt="DotNetKicks" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://www.google.com/bookmarks/mark?op=edit&amp;bkmk=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;title=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es&amp;annotation=%C2%A0As%C2%A0most%20can%20attest%20when%20launching%20into%20the%20world%20of%20WPF%20you%20have%20to%20jump%20in%20and%20hope%20you%20can%20figure%20out%20how%20to%20swim%20before%20you%20drown.%C2%A0%20It%20has%20a%20huge%20learning%20curve%20but%20the%20end%20results%20are%20usually%20pretty%20amazing.%0D%0A%0D%0ALINQ%2C%20on%20the%20other%20hand%2C%20you%20ca" title="Google Bookmarks"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/googlebookmark.png" title="Google Bookmarks" alt="Google Bookmarks" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="https://favorites.live.com/quickadd.aspx?marklet=1&amp;url=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;title=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es" title="Live"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/live.png" title="Live" alt="Live" class="sociable-hovers" /></a>
	<a rel="nofollow"  target="_blank" href="http://news.ycombinator.com/submitlink?u=http%3A%2F%2Fwww.formatexception.com%2F2008%2F09%2Ftiptoe-through-the-tulips-linqeseses%2F&amp;t=Tiptoe%20Through%20the%20Tulips%20...%20LINQeses...es" title="HackerNews"><img src="http://www.formatexception.com/wp-content/plugins/sociable/images/hackernews.png" title="HackerNews" alt="HackerNews" class="sociable-hovers" /></a>


<br/><br/>]]></content:encoded>
			<wfw:commentRss>http://www.formatexception.com/2008/09/tiptoe-through-the-tulips-linqeseses/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
