﻿<?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>Programming By A Tool &#187; C#</title>
	<atom:link href="http://byatool.com/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>To say I'm the best would be admitting I actually have competition.</description>
	<lastBuildDate>Wed, 28 Jul 2010 18:01:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>ByATool.com gets a shiny new tool!</title>
		<link>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/</link>
		<comments>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/#comments</comments>
		<pubDate>Wed, 31 Mar 2010 14:03:01 +0000</pubDate>
		<dc:creator>Andre</dc:creator>
				<category><![CDATA[Website News]]></category>
		<category><![CDATA[Writing]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1287</guid>
		<description><![CDATA[A while back, we put up an offer to write for our blog.  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this. ByATool.com Readers... Amy. Amy... ByATool.com Readers. Amy is a magnificent geek and almost 10 [...]]]></description>
			<content:encoded><![CDATA[<p>A while back, we put up an offer to write for our blog.  Only one has risen to the top as someone having both the technical know-how and the razor sharp wit required to write on a site such as this.</p>
<p>ByATool.com Readers... Amy.</p>
<p>Amy... ByATool.com Readers.</p>
<p>Amy is a magnificent geek and almost 10 year veteran of server administration  and software development. She has worked at IBM, Concurrent Technologies  Corporation, and University of Pittsburgh Medical Center.  Currently,  she is doing custom SharePoint development connected with Team  Foundation Server and the ASP.NET MVC framework development using the Entity  Framework, C#, and jQuery.  She is currently living in Pittsburgh and  not happy at all about commuting into a city with 3 rivers because of  the many bridges and no serious commuter subway systems... Who plans  this stuff?</p>
<p>Welcome Amy!</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/" title="ASP.Net MVC:  Quick Overview of Controller Structure">ASP.Net MVC:  Quick Overview of Controller Structure</a></li><li><a href="http://byatool.com/pontification/aspnet-mvc-is-the-use-of-jquery-asynchronous-calls-a-must/" title="ASP.Net MVC:  Is the Use of jQuery/Asynchronous calls a Must?">ASP.Net MVC:  Is the Use of jQuery/Asynchronous calls a Must?</a></li><li><a href="http://byatool.com/pontification/are-jquery-and-asynchronous-calls-against-mvc/" title="Are jQuery and Asynchronous Calls against MVC?">Are jQuery and Asynchronous Calls against MVC?</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Data Annotations, MVC, and Why You Might Like Them</title>
		<link>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/</link>
		<comments>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 18:01:40 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Data Annotations]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1155</guid>
		<description><![CDATA[So if you were like me before I knew what Data Annotations were, you most likely would be thinking, "What are Data Annotations?". Well I'm glad I can read your mind and therefore I am glad you asked. Now the fun part about this post is that I might have to admit I was wrong. [...]]]></description>
			<content:encoded><![CDATA[<p>So if you were like me before I knew what Data Annotations were, you most likely would be thinking, "What are Data Annotations?".  Well I'm glad I can read your mind and therefore I am glad you asked.</p>
<p>Now the fun part about this post is that I might have to admit I was wrong.  Why would that be?  Well in <a href="http://byatool.com/pontification/asp-net-mvc-quick-overview-of-controller-structure/">this post</a> I suggested that validation rules would be set in the controller.  Turns out, there is possibly a better place, on the model itself.  How can this be done???  Well that's what you're about to find out.</p>
<p>Say you have a user create model:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> AddUserModel
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> Password { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> RepeatPassword { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Now you could have a method on the controller like:</p>
<pre>  <span style="color: #0000ff;">publi</span>c <span style="color: #008080;">ActionResul</span>t AddUser(<span style="color: #008080;">AddUserMode</span>l model)
  {
    <span style="color: #0000ff;">if</span>(IsValid(model))
    {
      ...
    }
  }</pre>
<p>Where you have to create the IsValid method for every model on the controller that you need to validate (And possibly on other controllers if you are sharing models between them...) Or you can have this:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #008080;">ActionResult</span> AddUser(<span style="color: #008080;">AddUserModel</span> model)
  {
    <span style="color: #0000ff;">if</span>(<span style="color: #008080;">ModelState</span>.IsValid)
    {
      ...
    }
  }</pre>
<p>And that is already built in so no validation method needed.  But how is that possible?  Attributes on the model or namely the ValidationAttribute class.</p>
<p>First off you have to include the System.ComponentModel dll in the project.  Simple enough.  Please say you know how to do that or do me a favor and remind yourself to blink. OK done?  Good.</p>
<p>Now you can use some of the built in attributes which is good.  Things like required are nice:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> <span style="color: #008080;">UserName</span> { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<p>There you go.  Now if the UserName is null or empty, the ModelState will no longer be valid and will fail this check:</p>
<pre>  <span style="color: #008080;">ModelState</span>.IsValid</pre>
<p>Now you might wonder what the error message will be for that?  Honest answer:  I have no f--king clue.  That's why you can actually set it.  Those guys at Microsoft thought of everything.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">AddUserModel</span>
  {
    [<span style="color: #008080;">Required</span>(ErrorMessage = <span style="color: #800000;">"ENTER A USERNAME IDIOT!"</span>]
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">String</span> UserName { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    ...
  }</pre>
<blockquote><p>The guys in the legal department have told me I have to note that your error message should change depending on your use and you shouldn't use the one above.  Whatever.</p></blockquote>
<p>Now you might want to actually pass the errors back, and why wouldn't you?  You're a fine, upstanding, and thoughtful person and I lie like a crook.  The errors, if there are any, are in here:</p>
<pre>  ViewData.ModelState.Values</pre>
<p>And you can use two loops to get to all of them, but I think the parent loop will only run once.</p>
<pre>  <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelState</span> state <span style="color: #0000ff;">in</span> ViewData.ModelState.Values)
  {
    <span style="color: #0000ff;">foreach</span> (<span style="color: #008080;">ModelErro</span>r error <span style="color: #0000ff;">in</span> state.Errors)
    {
      messageList.Add(error.ErrorMessage);
    }
  }</pre>
<p>Pretty nice huh?  Maybe if you're an idiot who just learned about this.  For cool people like me, it's old news.</p>
<p>What's the point this?  If "this" is data annotations:  Well it helps move some of the validation off the controller if you are looking for a more "Fat model, skinny controller" design which I'm told is a good idea.  This also gets rid of all the validation methods and saves time because of it.</p>
<p>If "this" is your life?  I have no idea.  But if you're to the point that you're asking me about the meaning of your life, you are in some serious trouble.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/spark-view-engine-asp-net-mvc-and-you/" title="Spark View Engine, ASP.Net MVC, and You">Spark View Engine, ASP.Net MVC, and You</a></li><li><a href="http://byatool.com/mvc/custom-data-annotations-with-mvc-how-to-check-multiple-properties-at-one-time/" title="Custom Data Annotations With MVC: How to Check Multiple Properties at One Time">Custom Data Annotations With MVC: How to Check Multiple Properties at One Time</a></li><li><a href="http://byatool.com/add-on/random-add-on-automapper/" title="Random Add-On &#8211; Automapper">Random Add-On &#8211; Automapper</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Random Add-On &#8211; Automapper</title>
		<link>http://byatool.com/add-on/random-add-on-automapper/</link>
		<comments>http://byatool.com/add-on/random-add-on-automapper/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 16:23:16 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Add On]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1071</guid>
		<description><![CDATA[So if you've bothered reading my posts in the past, and don't worry cause I haven't, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don't, as I'm not bending the rule because I'm becoming a better person, just more lazy. This is [...]]]></description>
			<content:encoded><![CDATA[<p>So if you've bothered reading my posts in the past, and don't worry cause I haven't, you might have seen me express my rule about not wanting to use third party stuff. Well things change. Actually they don't, as I'm not bending the rule because I'm becoming a better person, just more lazy. This is where <span style="font-size:20px;font-weight:bold;"><a href="http://automapper.codeplex.com/">Automapper</a></span> comes in.</p>
<p><span style="font-size:20px;font-weight:bold;"><a href="http://automapper.codeplex.com/">Automapper</a></span> is pretty much what it sounds like, it maps class properties automatically. Maybe a more clevererest name would have been ClassPropertyAutoMapper, but the guys who made it shouldn't be persecuted for lacking creativity.</p>
<p>How simple is <span style="font-size:20px;font-weight:bold;"><a href="http://automapper.codeplex.com/">Automapper</a></span>? Simple enough that even you can use it. Now that's simple! Say you have two classes, a entity class and a model, and you want to map the model to the entity in the constructor. You could do:</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">SomeModel</span>
  {
    <span style="color: #0000ff;">public</span> SomeModel(<span style="color: #008080;">SomeEntity</span> someEntity)
   {
     SomeProperty = someEntity.SomeProperty;
   }
  }</pre>
<p>But where's the lazyiness? I expect so much less from you. But it's ok, salvation is right here:</p>
<pre>  <span style="color: #0000ff;">public</span> SomeModel(<span style="color: #008080;">SomeEntity</span> someEntity)
  {
    <span style="color: #008080;">Mapper</span>.CreateMap();
    <span style="color: #008080;">Mapper</span>.Map(someEntity, <span style="color: #0000ff;">this</span>);
  }</pre>
<p>But... but what if there are properties on SomeModel that don't directly map by name? Well, there's an ap...i for that. (Not sure that even makes sense but it was clever.)</p>
<pre>  <span style="color: #0000ff;">public</span> SomeModel(<span style="color: #008080;">SomeEntity</span> someEntity)
  {
    <span style="color: #008080;">Mapper</span>.CreateMap&lt;<span style="color: #008080;">FiftyPostUser</span>, <span style="color: #008080;">UserInfoViewModel</span>&gt;()
     .ForMember(test =&gt; test.Status, tester =&gt; tester.MapFrom(item =&gt; item.Status.ToString()));
    <span style="color: #008080;">Mapper</span>.Map(someEntity, <span style="color: #0000ff;">this</span>);
  }</pre>
<p>So I know you're thinking that there's a catch, well there is. You have to actually get the <a href="http://automapper.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=32994">dll and reference in your project</a>. I know! Work is hard. Why can't these guys just come to your place of work/home/mom's basement and do it for you? What kind of world is it when you can't get all that for free? Personally, I hate it.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li><li><a href="http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/" title="Entity Framework: Possible Lazy Loading Solution">Entity Framework: Possible Lazy Loading Solution</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/add-on/random-add-on-automapper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>State List in Dictionary Form</title>
		<link>http://byatool.com/pointless/state-list-in-dictionary-form/</link>
		<comments>http://byatool.com/pointless/state-list-in-dictionary-form/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 14:55:34 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pointless]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1077</guid>
		<description><![CDATA[Tired of having to look this up from time to time, so I'm putting this here for my own use. If you get something out of it, good for you. In the end, I really don't care. public Dictionary GetAllStates() { if(_stateList == null) { _stateList = new Dictionary(); _stateList.Add("Alabama","AL"); _stateList.Add("Alaska","AK"); _stateList.Add("American Samoa","AS"); _stateList.Add("Arizona","AZ"); _stateList.Add("Arkanas","AR"); [...]]]></description>
			<content:encoded><![CDATA[<p>Tired of having to look this up from time to time, so I'm putting this here for my own use.  If you get something out of it, good for you.  In the end, I really don't care.</p>
<pre>
    public Dictionary<string, string> GetAllStates()
    {
      if(_stateList == null)
      {
        _stateList = new Dictionary<string, string>();

        _stateList.Add("Alabama","AL");
        _stateList.Add("Alaska","AK");
        _stateList.Add("American Samoa","AS");
        _stateList.Add("Arizona","AZ");
        _stateList.Add("Arkanas","AR");
        _stateList.Add("California","CA");
        _stateList.Add("Colorado","CO");
        _stateList.Add("Connecticut","CT");
        _stateList.Add("Delaware","DE");
        _stateList.Add("District Of Colombia","DC");
        _stateList.Add("Federated States Of Micronesia","FM");
        _stateList.Add("Florida","FL");
        _stateList.Add("Georgia","GA");
        _stateList.Add("Guam","GU");
        _stateList.Add("Hawaii","HI");
        _stateList.Add("Idaho","ID");
        _stateList.Add("Illinois","IL");
        _stateList.Add("Indiana","IN");
        _stateList.Add("Iowa","IA");
        _stateList.Add("Kansas","KS");
        _stateList.Add("Kentucky","KY");
        _stateList.Add("Lousiana","LA");
        _stateList.Add("Maine","ME");
        _stateList.Add("Marshall Islands","MH");
        _stateList.Add("Maryland","MD");
        _stateList.Add("Massachusetts","MA");
        _stateList.Add("Michigan","MI");
        _stateList.Add("Minnesota","MN");
        _stateList.Add("Mississippi","MS");
        _stateList.Add("Missouri","MO");
        _stateList.Add("Montana","MT");
        _stateList.Add("Nebraska","NE");
        _stateList.Add("Nevada","NV");
        _stateList.Add("New Hampshire","NH");
        _stateList.Add("New Jersey","NJ");
        _stateList.Add("New Mexico","NM");
        _stateList.Add("New York","NY");
        _stateList.Add("North Carolina","NC");
        _stateList.Add("North Dakota","ND");
        _stateList.Add("Northern Mariana Islands","MP");
        _stateList.Add("Ohio","OH");
        _stateList.Add("Oklahoma","OK");
        _stateList.Add("Oregon","OR");
        _stateList.Add("Palau","PW");
        _stateList.Add("Pennsylvania","PA");
        _stateList.Add("Puerto Rico","PR");
        _stateList.Add("Rhode Island","RI");
        _stateList.Add("South Carolina","SC");
        _stateList.Add("South  Dakota","SD");
        _stateList.Add("Tennessee","TN");
        _stateList.Add("Texas","TX");
        _stateList.Add("Utah","UT");
        _stateList.Add("Varmont","VT");
        _stateList.Add("Virgin Islands","VI");
        _stateList.Add("Virginia","VA");
        _stateList.Add("Washington","WA");
        _stateList.Add("West Virginia","WV");
        _stateList.Add("Wisconsin","WI");
        _stateList.Add("Wyoming","WY");
      }

      return _stateList;
    }
</pre>
<p>So there.  Hope you're happy.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/" title="By Reference in C# and How to Get Schooled By It">By Reference in C# and How to Get Schooled By It</a></li><li><a href="http://byatool.com/pontification/static-abstract-should-i-bother/" title="Static Abstract &#8230; should I bother?">Static Abstract &#8230; should I bother?</a></li><li><a href="http://byatool.com/utilities/quick-linq-thing-string-to-number-string/" title="Convert a String to a Number String With Linq&#8230; YAY">Convert a String to a Number String With Linq&#8230; YAY</a></li><li><a href="http://byatool.com/c/i-are-tupid/" title="I are tupid">I are tupid</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pointless/state-list-in-dictionary-form/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Framework: Possible Lazy Loading Solution</title>
		<link>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/</link>
		<comments>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 14:53:02 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=713</guid>
		<description><![CDATA[So been a while since I posted last, and I'm sure everyone has been worried. Turns out that I've been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I've been working one, [...]]]></description>
			<content:encoded><![CDATA[<p>So been a while since I posted last, and I'm sure everyone has been worried. Turns out that I've been banging my head against the wall named MVC. And man I have a slew of new posts back logged for when I have more time. However, due to the new project I've been working one, I forced myself to tackle Lazy Loading in the Entity Framework. Turns out the solution isn't that hard since it has everything needed to make it work.</p>
<p>One of the biggest waaaaahbumlance calls is the fact that Entity Framework doesn't have lazy loading. This isn't true. It does, you just have to do a little work, which is to be expected from a FRAMEWORK. Now I have to admit, I wish there were a slightly less odd way of doing this, but eh it's not too bad.</p>
<p>Say you have a class named Topic and it has a reference to a Forum class named ParentForum. Now this is just a property on the actual class created by the E-Work to represent a many to one foriegn key relationship between the Topic table and the Forum table. Now the problem comes in when you try to use something from that property like:</p>
<pre>    <span style="color: #008080;">Int32</span> someInt = topic.ParentForum.ForumId;</pre>
<p>If you didn't use the Include method when you got that topic:</p>
<pre>    context.Include(<span style="color: #800000;">"ParentForum"</span>).Select(topic =&gt; topic);</pre>
<p>You are screwed because the ParentForum property will return a null. So this forces you to use Include every time you want to get a Topic and access it's ParentForum property. Sucks.</p>
<p>So next thought is to find out how to lazy load and then plunk it into that generated property. Eh I don't know about you, but that sounds like a bad idea to mess around with a generated file. You have no idea when the E-Work will just trash the file and rebuild.</p>
<p>Next thought was to create a proxy property to check the real one and then load if it's not already loaded. Something like:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Forum</span> ParentForumLazyLoaded
    {
        <span style="color: #0000ff;">get</span>
        {
           <span style="color: #008000;">//check and return</span>
        }
    }</pre>
<p>Ok so that's not horrible except two things: The name looks dumb and people can still get at the original ParentForum property.</p>
<p>So in comes my solution and it's pretty simple. Rename the property name on the class to something ParentForumInner and make it private.</p>
<pre><img class="alignnone size-full wp-image-714" title="bat_lazyload1" src="http://byatool.com/wp-content/uploads/2009/06/bat_lazyload1.jpg" alt="bat_lazyload1" width="598" height="263" /></pre>
<p>Then you can create a much nicer outward facing property like:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Forum</span> ParentForum
    {
      <span style="color: #0000ff;">get</span>
      {
          <span style="color: #0000ff;">if</span> (!ParentForumInnerReference.IsLoaded)
          {
              ParentForumInnerReference.Load();
          }

        <span style="color: #0000ff;">return</span> ParentForumInner;
    }
    <span style="color: #0000ff;">set</span>
    {
        ParentForumInner = <span style="color: #0000ff;">value</span>;
    }
}</pre>
<p>Now one of the issues with this is that although outside the class only the ParentForum property can be seen, within the class they both can be seen which can lead to issues like:</p>
<pre>    context.Topics.Where(topic =&gt; topic.ParentForum.ForumId == id);  <span style="color: #008000;">//boom</span></pre>
<p>Where you should be using:</p>
<pre>    context.Topics.Where(topic =&gt; topic.ParentForumInner.ForumId == id);  <span style="color: #008000;">//yay</span></pre>
<p>E-Work doesn't know how to handle that situation when evaluating that expression and the kicker is that it does just fine compile time. You won't know this is bad until runtime.</p>
<p>Other issue is that you have to do a little more work then just some setting on the property which is what most people wish for. I guess that may be true, but again this is a framework. It gives you all the tools you need to makes things work, you just have to do some coding.</p>
<p>The plus side to this is that with minimal coding, you can completely get rid of Include which to me is huge.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/add-on/random-add-on-automapper/" title="Random Add-On &#8211; Automapper">Random Add-On &#8211; Automapper</a></li><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/entity-framework-possible-lazy-loading-solution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>By Reference in C# and How to Get Schooled By It</title>
		<link>http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/</link>
		<comments>http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 20:10:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Referece]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=114</guid>
		<description><![CDATA[WARNING: If you understand The concept of By Reference, skip the first part of this post: So you have an object, huh? Ok well what does that mean? Basically there is a stack and a heap. When you declare an object, space is made on the stack, basically it's a placeholder saying that there will [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #800000;">WARNING: If you understand The concept of By Reference, skip the first part of this post:</span></p>
<p>So you have an object, huh? Ok well what does that mean? Basically there is a stack and a heap. When you declare an object, space is made on the stack, basically it's a placeholder saying that there will be something to point.</p>
<pre>    <span style="color: #33cccc;">User</span> someUser;</pre>
<p>Now when you instatiate:</p>
<pre>    someUser = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">User</span>();</pre>
<p>That user Object is put on the heap and that placeholder (reference) on the stack? Well it's given a pointer which SURPRISE points to the object on the heap. Now when you pass the object into the method, you aren't really passing what's on the heap. You are actually copying and passing the pointer. Inside the method, a new entry is thrown on the stack that points to the same object on the heap. This way if you change anything on the object in the method, the changes are reflected outside the method. (Say if you added items to a list in the method) Now this all changes if the object inside the method is reinitialized or repointed:</p>
<pre>    SomeMethod(<span style="color: #33cccc;">User</span> user)
    {
        user = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">User</span>();
        user.UserName = <span style="color: #800000;">"Sean"</span>;
    }</pre>
<p>Remember that user we passed in? It now has nothing to do with the one in the method now. There is now a new object on the heap and "user" in the method now points to it. Why did I tell you all of this?</p>
<p><span style="color: #800000;">END REFERENCE EXPLANATION:</span></p>
<p>Say you have this:</p>
<pre>    ...

    <span style="color: #33cccc;">UserList</span> userList = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">UserList</span>();
    <span style="color: #33cccc;">SomeList</span> list = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">SomeList</span>();</pre>
<pre>    FillListFromUserList(list, userList);

    ...

    <span style="color: #0000ff;">void</span> FillListFromUser(<span style="color: #33cccc;">SomeList</span> listToCopyTo, <span style="color: #33cccc;">UserList</span> userList)
    {
       <span style="color: #0000ff;">foreach</span>(<span style="color: #33cccc;">User</span> currentUser <span style="color: #0000ff;">in</span> userList)
       {
          listToCopyTo.Add(userList);
       }
    }</pre>
<p>Easy, and basically at this point list should have the same items as userList. Now say list needs what's in userList but in order by UserID. Suppose you did it like this:</p>
<pre>    <span style="color: #0000ff;">void</span> FillListFromUser(<span style="color: #33cccc;">SomeList</span> listToCopyTo, <span style="color: #33cccc;">UserList</span> userList)
    {
       <span style="color: #0000ff;">foreach</span>(<span style="color: #33cccc;">User</span> currentUser in userList)
       {
          listToCopyTo.Add(userList);
       }

       <span style="color: #0000ff;">var</span> sorted = <span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> userList
                    <span style="color: #0000ff;">orderby</span> user.UserID
                    <span style="color: #0000ff;">select</span> user;

       listToCopy = sorted.ToList();
    }</pre>
<p>Ok so a quick check to see if list now contains items will show it does. Now say you looked at this method and thought it was a little more than needed. You decide to do this:</p>
<pre>    <span style="color: #0000ff;">void</span> FillListFromUser(<span style="color: #33cccc;">SomeList</span> listToCopyTo, <span style="color: #33cccc;">UserList</span> userList)
    {
        listToCopyTo = userList.OrderBy(user =&gt; user.ID);
    }</pre>
<p>Now a quick check to see if list has something in it shows that it doesn't. But wait, what the hell? The first one worked and the second is just short hand right? Eh well the problem is how objects are passed. By reference means that it doesn't pass the original pointer from the stack but it copies it so that there are two references on the stack that point to the same object on the heap. What does this all mean? Well both</p>
<pre>    listToCopy = sorted.ToList();
 And
    listToCopyTo = userList.OrderBy(user =&gt; user.ID);</pre>
<p>Have now reset the pointer for the reference in the method (listToCopyTo) making it no longer have anything to do with the list outside of it (list). The reason why it gave a false positive on the first one was that I had added to the list within, and therefor to the object the list outside points to. So the changing of the pointer:</p>
<pre>    listToCopy = sorted.ToList();</pre>
<p>would no longer affect the list oustide. However, in the second example I never added to the object they both pointed to before I changed the pointer on the inner. Hense why the second example had nothing in the outer list. To make matters worse I would have noticed this before if the original userList hadn't been sorted by ID already.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li><li><a href="http://byatool.com/pontification/static-abstract-should-i-bother/" title="Static Abstract &#8230; should I bother?">Static Abstract &#8230; should I bother?</a></li><li><a href="http://byatool.com/utilities/quick-linq-thing-string-to-number-string/" title="Convert a String to a Number String With Linq&#8230; YAY">Convert a String to a Number String With Linq&#8230; YAY</a></li><li><a href="http://byatool.com/c/i-are-tupid/" title="I are tupid">I are tupid</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C#, Var, and Objec-  Propert-  I have no idea what the term is</title>
		<link>http://byatool.com/pontification/c-var-and-objec-propert-i-have-no-idea-what-the-term-is/</link>
		<comments>http://byatool.com/pontification/c-var-and-objec-propert-i-have-no-idea-what-the-term-is/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 15:31:26 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Anonymous Types]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Duck Typing]]></category>
		<category><![CDATA[Dynamic]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=98</guid>
		<description><![CDATA[So I caugh this the other day and I'm not really sure it's useful but it got me thinking... Say you have a string and you want to create what ReSharper calls a "implicitly typed local variable declaration", or as most people know it as "var", and intialize it with a created value: String someThing [...]]]></description>
			<content:encoded><![CDATA[<p>So I caugh this the other day and I'm not really sure it's useful but it got me thinking...</p>
<p>Say you have a string and you want to create what ReSharper calls a "implicitly typed local variable declaration", or as most people know it as "var", and intialize it with a created value:</p>
<pre>  <span style="color: #33cccc;">String</span> someThing = <span style="color: #800000;">"hi"</span>;
  <span style="color: #0000ff;">var</span> onTheFly = <span style="color: #0000ff;">new</span> { someThing };</pre>
<p>And now you can do this:</p>
<pre>  <span style="color: #33cccc;">String</span> somethingElse = ontTheFly.something;</pre>
<p>What it basically did was not only take the value of the string, but the name too and made a property on the var. In fact you may have seen this already with Linq:</p>
<pre>    <span style="color: #0000ff;">var</span> hi = <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> test
               <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> {item.UserRole};

    <span style="color: #33cccc;">UserRole</span> someRole = hi.ToList()[0].UserRole;</pre>
<p>So what does this all mean? Right now, I'm not really sure. I suppose if you have a method that you want to combine a bunch of value/objects into one var so you don't have to keep refering to 8 different objects that might work:</p>
<pre>    <span style="color: #008000;">//Get the user
</span>    <span style="color: #33cccc;">User</span> user = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">User</span> (1);
    <span style="color: #008000;">//Get some icecream... couldn't think of any better fake class name</span>
    <span style="color: #33cccc;">IceCream</span> iceCream = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">IceCream</span>(1);

    <span style="color: #0000ff;">var</span> stuff = <span style="color: #0000ff;">new</span> { user.UserName, user.UserRoles, user.UserLastName,
                             iceCream.Flavor, iceCream.Texture };

    <span style="color: #008000;">//IMAGINARY CODE GOES HERE</span>
    <span style="color: #008000;">//MORE IMAGINARY CODE</span>
    <span style="color: #008000;">//??</span>
    <span style="color: #008000;">//PROFIT</span>
    <span style="color: #0000ff;">if</span>(stuff.UserName.Equals(<span style="color: #800000;">"Sean"</span>, StringComparison.OrdinalIgnoreCase)
       &amp;&amp; stuff.Flavor == IceCreamFlavor.Chocolate)
    {
       <span style="color: #008000;">//BLAH BLAH BLAH
</span>    }</pre>
<p>As you can see, it could be a way to group together a bunch of things in a method, but I'm not sure that is really useful.</p>
<p><span style="color: #800000;">*WARNING THIS IS NOT TO BE TAKEN AS FACT, JUST MUSINGS OF AN IDIOT*</span></p>
<p>Now for the theory... As is, this isn't useful but with 4.0 that might change with Duck Typing and dynamic types. Why? Well take a method like this:</p>
<pre>    CallMe(userName, userFirstName, userLastName, userAddress,
             thisIsStupid, makeItEnd, iNeedAnAdult... endMe);</pre>
<p>Now that's a lot of parameters. Conventional wisdom says I should create a new class whose properties match the parameters I would be sending in and just send in that class:</p>
<pre>    parameterClass.UserName = userName;
    parameterClass.UserFirstName = firstName;
    .....
    CallMe(parameterClass);</pre>
<p>Now the only annoying thing is having to make the class to do this. What if dynamic types + duck typing takes that step away?</p>
<pre>    <span style="color: #0000ff;">var</span> parameter = <span style="color: #0000ff;">new</span> { userName, userFirstName, userLastName .... };
    CallMe(parameter);</pre>
<p>Then CallMe would take in a dynamic type and just look to see if it has the needed properties. Would be nice if this is possible but I haven't used 4.0 yet to know, I'm only guessing from what I've read.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/the-switch-remover/" title="The Switch Remover: Convert Switch Statements to Dictionaries">The Switch Remover: Convert Switch Statements to Dictionaries</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/general-coding/orderby-using-a-property-name/" title="Dynamic Linq: OrderBy Using a String for a Property Name">Dynamic Linq: OrderBy Using a String for a Property Name</a></li><li><a href="http://byatool.com/lessons/and-then-you-hit-the-wall/" title="And then you hit the wall.">And then you hit the wall.</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/c-var-and-objec-propert-i-have-no-idea-what-the-term-is/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</title>
		<link>http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/</link>
		<comments>http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/#comments</comments>
		<pubDate>Thu, 13 Nov 2008 03:09:38 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=86</guid>
		<description><![CDATA[Today I was writing out an example of why the extension methods are for the most part better to use than the querying language. Go figure I would find a case where that's not entirely true. Say you are using these three funcs: Func&#60;User, String&#62; userName = user =&#62; user.UserName; Func&#60;User, Boolean&#62; userIDOverTen = user [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was writing out an example of why the extension methods are for the most part better to use than the querying language.  Go figure I would find a case where that's not entirely true.  Say you are using these three funcs:</p>
<pre><span style="color: #33cccc;">    Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">String</span>&gt; userName = user =&gt; user.UserName;
<span style="color: #33cccc;">    <span>Func</span></span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; userIDOverTen = user =&gt; user.UserID &lt; 10;
<span style="color: #33cccc;">    <span>Func</span></span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; userIDUnderTen = user =&gt; user.UserID &gt; 10;</pre>
<p>As you can see the first one replaces the lamdba expression to get the user name, the second replaces a lamdba expression used to check if the ID is lower than 10, and let's face it, the third should be pretty easy to understand now.</p>
<p>NOTE:  This is a  silly example but it works.</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> userList =
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> userList
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">where</span> userIDOverTen(user)
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">select</span> userName;
Versus

<span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> otherList =
<span style="color: #33cccc;">      </span>userList
<span style="color: #33cccc;">      </span>.Where(IDIsBelowNumber)
<span style="color: #33cccc;">      </span>.Select(userName)</pre>
<p>In this example, the second is a little less verbose since the extension method can make full use of the Func, but he Linq expression can't since it is look just for a Boolean rather than a Func that returns boolean.   However, this is where it might be better to use the expression language.  Say you already had a method that takes in more than just a user:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">private</span> <span style="color: #33cccc;">Boolean</span> IDIsBelowNumber(<span style="color: #33cccc;">User</span> user, <span style="color: #33cccc;">Int32</span> someNumber, <span style="color: #33cccc;">Boolean</span> doSomething)
<span style="color: #33cccc;">    </span>{
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">return</span> user.UserID &lt; someNumber;
    }</pre>
<p>Note:  doSomething is just there because of the where extension method being ok with a method that takes in a user and integer and returns boolean.  Kind of annoying for this example.</p>
<p>Now if you look at the Linq query:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> completeList =
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">from</span> user <span style="color: #0000ff;">in</span> userList
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">where</span> userIDOverTen(user, 10)
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">select</span> userName;</pre>
<p>You're good for it.  Now the Extension Method:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> otherList =
<span style="color: #33cccc;">      </span>userList
<span style="color: #33cccc;">      </span>.Where(IDIsBelowNumber????)
<span style="color: #33cccc;">      </span>.Select(userName)</pre>
<p>Without a lambda expression, I really can't call that method.  So now what I have to do is create a method that creates a Func based off the original method call.</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">private</span> <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; IDIsBelowNumberFunc(<span style="color: #33cccc;">Int32</span> number)
<span style="color: #33cccc;">    </span>{
<span style="color: #33cccc;">      </span><span style="color: #0000ff;">return</span> user =&gt; IDIsBelowNumber(user, number, <span style="color: #0000ff;">true</span>);
<span style="color: #33cccc;">    </span>}</pre>
<p>And then plug it in:</p>
<pre><span style="color: #33cccc;">    </span><span style="color: #0000ff;">var</span> otherList =
<span style="color: #33cccc;">      </span>userList
<span style="color: #33cccc;">      </span>.Where(IDIsBelowNumberFunc(10))
<span style="color: #33cccc;">      </span>.Select(userName)</pre>
<p>What does this all mean?  You just lost 5 minutes of your life.  I hope it was worth it.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/net-issues/funcs-type-inference-and-linq-and-bears-oh-my/" title="Cannot Resolve Method, Can&#8217;t Infer Return Type, and Funcs">Cannot Resolve Method, Can&#8217;t Infer Return Type, and Funcs</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Static Abstract &#8230; should I bother?</title>
		<link>http://byatool.com/pontification/static-abstract-should-i-bother/</link>
		<comments>http://byatool.com/pontification/static-abstract-should-i-bother/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 20:00:58 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=68</guid>
		<description><![CDATA[So it came up recently that someone was bummed that you can't create a static abstract method. Now conceptually, this is blocked by C# but I came up with this "work around"... And I have no idea if I would ever use it. This was more of a "Do it because I can" rather than [...]]]></description>
			<content:encoded><![CDATA[<p>So it came up recently that someone was bummed that you can't create a static abstract method.  Now conceptually, this is blocked by C# but I came up with this "work around"... And I have no idea if I would ever use it.  This was more of a "Do it because I can" rather than "Do it because I should."</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">abstract</span> <span style="color: #0000ff;">class</span> <span style="color: #33cccc;">Parent</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">abstract</span> <span style="color: #33cccc;">String</span> ReturnAValue(<span style="color: #33cccc;">String</span> returnThis);

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #33cccc;">String</span> ReturnAValue(<span style="color: #33cccc;">String</span> returnThis) <span style="color: #0000ff;">where</span> K : <span style="color: #33cccc;">Parent</span>
    {
        K classToCreate;

        classToCreate = Activator.CreateInstance();
        <span style="color: #0000ff;">return</span> classToCreate.ReturnAValue(returnThis);
    }
  }</pre>
<p>So what I did here was create a parent class that causes any child to override the ReturnAValue method so that I could create a static method on the parent that basically would just instantiate the child class and call the overridden method. How's that for a run on sentence?</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #33cccc;">ChildA</span> : <span style="color: #33cccc;">Parent</span>
  {
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">override</span><span style="color: #33cccc;"> String</span> ReturnAValue(<span style="color: #33cccc;">String</span> returnThis)
    {
        <span style="color: #0000ff;">return</span> <span style="color: #ff0000;">"ChildA "</span> + returnThis;
    }
  }</pre>
<p>And this in full use:</p>
<pre>  <span style="color: #33cccc;">String</span> testReturn;
  testReturn = Parent.ReturnAValue(<span style="color: #ff0000;">"returned"</span>);</pre>
<p>Can you guess what that returns? If you can, you're special. You might wonder why I have to use generics in this. Well I mean you could do this:</p>
<pre>    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #33cccc;">String</span> ReturnAValue(<span style="color: #33cccc;">Parent</span> returnThis)
    {
        <span style="color: #0000ff;">return</span> returnThis.ReturnAValue(returnThis);
    }
</pre>
<p>But that assumes you have to instantiate the child and pass it in.</p>
<p>Now the main problem with this, beyond the fact that you'll probably never use this, is Activator.CreateInstance() need a default public constructor to use. Kind of a catch.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li><li><a href="http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/" title="By Reference in C# and How to Get Schooled By It">By Reference in C# and How to Get Schooled By It</a></li><li><a href="http://byatool.com/utilities/quick-linq-thing-string-to-number-string/" title="Convert a String to a Number String With Linq&#8230; YAY">Convert a String to a Number String With Linq&#8230; YAY</a></li><li><a href="http://byatool.com/c/i-are-tupid/" title="I are tupid">I are tupid</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/static-abstract-should-i-bother/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Switch Remover: Convert Switch Statements to Dictionaries</title>
		<link>http://byatool.com/general-coding/the-switch-remover/</link>
		<comments>http://byatool.com/general-coding/the-switch-remover/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 13:30:10 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[Action]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Lambda]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=65</guid>
		<description><![CDATA[Folks, what if I told you that Switch is a thing of the past? What if I told you I had a way to reduce code in certain areas so that you don't have that messy Switch logic? What would you pay for that? Would you pay $19.95? Not convinced? Well take this: switch(someDropDownList.SelectedValue) { [...]]]></description>
			<content:encoded><![CDATA[<p>Folks, what if I told you that Switch is a thing of the past? What if I told you I had a way to reduce code in certain areas so that you don't have that messy Switch logic? What would you pay for that? Would you pay $19.95? Not convinced? Well take this:</p>
<pre>  <span style="color: #0000ff;">switch</span>(someDropDownList.SelectedValue)
  {
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"hi"</span>:
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        <span style="color: #0000ff;">break</span>;
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"there"</span>:
        CallThisMethod();
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        <span style="color: #0000ff;">break</span>;
  }</pre>
<p>And I'll give you this:</p>
<pre>  doSomething[someDropDownList.SelectedValue]();</pre>
<p>I bet you're ready to pay $19.95, but wait there's more. I'll actually throw in how I did such an amazing thing.</p>
<pre>  <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&gt; switchRemover = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&gt;();
  switchRemover.Add(<span style="color: #ff0000;">"hi"</span>, () =&gt; RunHiMethod();
  switchRemover.Add(<span style="color: #ff0000;">"there"</span>, () =&gt; RunThereMethod();</pre>
<p>Why that's amazing! But wait, I must be pulling something. What are these RunHiMethod and RunThereMethod methods? I must be pulling a fast one. Well, all they are is what the switch was doing before all wrapped up into one method. Don't get it?</p>
<pre>  <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">void</span> RunHiMethod()
  {
      CallThisMethod();
      CallThatMethod();
      CallAnotherMethod();
  }</pre>
<p>But... but what if I had to pass something in? What would I do then??? Boy you got me there, I could tell you but I'd have to charge you more. Wait... I'll even throw that in for free. That's right. Remember that old mess we had?</p>
<pre>  <span style="color: #0000ff;">switch</span>(someDropDownList.SelectedValue)
  {
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"hi"</span>:
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        <span style="color: #0000ff;">break</span>;
     <span style="color: #0000ff;">case</span> <span style="color: #ff0000;">"there"</span>:
        CallThisMethod(someUser);
        CallThatMethod();
        CallAnotherMethod();
        CallSomethingElse();
        <span style="color: #0000ff;">break</span>;
}</pre>
<p>Well shoot,we could do something like this:</p>
<pre>  <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&lt;<span style="color: #33cccc;">User</span>&gt;&gt; switchRemover = <span style="color: #0000ff;">new</span> <span style="color: #33cccc;">Dictionary</span>&lt;<span style="color: #33cccc;">String</span>, <span style="color: #33cccc;">Action</span>&gt;();
  switchRemover.Add(<span style="color: #ff0000;">"hi"</span>, currentUser =&gt; RunHiMethod(currentUser);
  switchRemover.Add(<span style="color: #ff0000;">"there"</span>, currentUser =&gt; RunThereMethod(currentUser );</pre>
<p>And then:</p>
<pre>  doSomething[someDropDownList.SelectedValue](currentUser);</pre>
<p>That's amazing! You ready with your credit card? I knew you would be.</p>
<p>The Switch Remover does not come with a warranty.<br />
The Switch Remover can not be used in all circumstances.<br />
The Switch Remover assumes no fault for any physical conditions caused by the sudden surge of awesomeness you might feel.</p>
<p>SO BUY IT NOW!</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/and-some-days-i-love-programming/" title="And some days I love programming">And some days I love programming</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/the-switch-remover/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Uhg It Won&#8217;t End</title>
		<link>http://byatool.com/general-coding/uhg-it-wont-end/</link>
		<comments>http://byatool.com/general-coding/uhg-it-wont-end/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 17:22:58 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=60</guid>
		<description><![CDATA[Still on the readability thing, but there was a second argument in the post that inspired now what is three posts of my own here. The question was should you use Linq based on people saying it's more readable, therefore just making it syntax sugar. foreach(Item current in itemList) { itemNameList.Add(current.Name); } Versus var itemNameList [...]]]></description>
			<content:encoded><![CDATA[<p>Still on the readability thing, but there was a second argument in the <a title="HERHEHREHRE" href="http://keithelder.net/blog/archive/2008/10/08/Balancing-Readability-and-New-Syntax-Sugar-in-C-3.0.aspx">post</a> that inspired now what is three posts of my own here. The question was should you use Linq based on people saying it's more readable, therefore just making it syntax sugar.</p>
<pre>  <span style="color: #0000ff;">foreach</span>(<span style="color: #33cccc;">Item</span> current <span style="color: #0000ff;">in</span> itemList)
  {
     itemNameList.Add(current.Name);
  }</pre>
<p>Versus</p>
<pre> <span style="color: #0000ff;">var</span> itemNameList = <span style="color: #0000ff;">from</span> item <span style="color: #0000ff;">in</span> itemList
                    <span style="color: #0000ff;">select</span> item.Name;</pre>
<p>Or</p>
<pre>  <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">Item</span>, <span style="color: #33cccc;">String</span>&gt; itemName = current =&gt; current.Name;
  itemNameList.Select(itemName);</pre>
<p>So at this point it's really a matter of preference. Problem is, you have to look closer to why the third is so much more than syntax yummies.</p>
<p>Say you want a method that takes in a UserList and you want to select all the users that have a property (Could be name, address, whatever) that matches a string. Well you could do this:</p>
<pre> <span style="color: #0000ff;">public</span> <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; AllUsersThatMatch(<span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; userList, <span style="color: #33cccc;">NeededProperty </span>property, <span style="color: #33cccc;">String </span>value)
 {
    <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; returnList;

    returnList = <span style="color: #0000ff;">new</span> List();

    <span style="color: #0000ff;">foreach</span>(UserItem currentUser <span style="color: #0000ff;">in</span> userList)
    {
        <span style="color: #0000ff;">switch</span>(property)
        {
            <span style="color: #0000ff;">case</span>(NeededProperty.Name):
                <span style="color: #0000ff;">if</span>(currentUser.Name == value)
                {
                    userList.Add(currentUser);
                }
                <span style="color: #0000ff;">break</span>;
            <span style="color: #0000ff;">case</span>(NeededProperty.Phone):
                <span style="color: #0000ff;">if</span>(currentUser.Phone == value)
                {
                    userList.Add(currentUser);
                }
                <span style="color: #0000ff;">break</span>;
        }
    }
 }</pre>
<p>Or you could do this:</p>
<pre> <span style="color: #0000ff;">public</span> <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; MatchesProperty(<span style="color: #33cccc;">NeededProperty </span>property, <span style="color: #33cccc;">String</span> value)
 {
    <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">User</span>, <span style="color: #33cccc;">Boolean</span>&gt; returnValue;

    <span style="color: #0000ff;">switch</span>(property)
    {
        <span style="color: #0000ff;">case</span> <span style="color: #33cccc;">NeededProperty</span>.Name:
            returnValue = currentItem =&gt; currentItem.Name == value;
            <span style="color: #0000ff;">break</span>;
        <span style="color: #0000ff;">case</span> <span style="color: #33cccc;">NeededProperty</span>.Phone:
            returnValue = currentItem =&gt; currentItem.Phone == value;
            <span style="color: #0000ff;">break</span>;
    }
    <span style="color: #0000ff;">return</span> returnValue;
  }

 <span style="color: #0000ff;">public</span> <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; AllUsersThatMatch(<span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt; userList, <span style="color: #33cccc;">NeededProperty </span>property, <span style="color: #33cccc;">String </span>value)
 {
    <span style="color: #33cccc;">IList</span>&lt;<span style="color: #33cccc;">User</span>&gt;  returnList;

    returnList = userList.Where(MatchesProperty(property, value));
    <span style="color: #0000ff;">return</span> returnList;
 }</pre>
<p>Now which do you think is easier to upkeep? For those of you wondering what I did, I simply used a method that would return the Func I needed for the passed in Enum and called it in the Where clause. The amount of code is probably close to the same right now, but add in 5 more values for the NeededProperty enum and you'll see the code amount differing more and more.</p>
<p>I realize this isn't the best of example, and probably the first way could be refactored but the idea is still there. The Linq Method approach gives you a lot more flexibility in the long run with dynamic stuff like this.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/and-some-days-i-love-programming/" title="And some days I love programming">And some days I love programming</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/uhg-it-wont-end/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What Is Readable Addon</title>
		<link>http://byatool.com/pontification/what-is-readable-addon/</link>
		<comments>http://byatool.com/pontification/what-is-readable-addon/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 15:03:43 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=58</guid>
		<description><![CDATA[Quick thought too about which to use due to readability: var you = from factor in seansAwesomeness select new FactorLite { Amount = amount; }; or you could do: Func&#60;Person, FactorLite&#62; selectFactorLite = currentFactor =&#62; new FactorLite { Amount = currentFactor.Amount }; seansAwesomeness.Select(selectFactorLite); I guess it's a matter of preference, but the first seems way [...]]]></description>
			<content:encoded><![CDATA[<p>Quick thought too about which to use due to readability:</p>
<pre><span style="color: #0000ff;">var</span> you = <span style="color: #0000ff;">from</span> factor <span style="color: #0000ff;">in</span> seansAwesomeness
          <span style="color: #0000ff;">select</span> <span style="color: #0000ff;">new</span> FactorLite
          {
             Amount = amount;
          };</pre>
<p>or you could do:</p>
<pre><span style="color: #00ccff;">Func</span>&lt;<span style="color: #00ccff;">Person</span>, <span style="color: #00ccff;">FactorLite</span>&gt; selectFactorLite = currentFactor =&gt; <span style="color: #0000ff;">new</span> <span style="color: #00ccff;">FactorLite </span>{ Amount = currentFactor.Amount };

seansAwesomeness.Select(selectFactorLite);</pre>
<p>I guess it's a matter of preference, but the first seems way too verbose for something too simple.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/net-issues/funcs-type-inference-and-linq-and-bears-oh-my/" title="Cannot Resolve Method, Can&#8217;t Infer Return Type, and Funcs">Cannot Resolve Method, Can&#8217;t Infer Return Type, and Funcs</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/what-is-readable-addon/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What Is Readable</title>
		<link>http://byatool.com/pontification/what-is-readable/</link>
		<comments>http://byatool.com/pontification/what-is-readable/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 14:51:57 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[FizzBuzz]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=56</guid>
		<description><![CDATA[So a couple of posts I read recently have been about readability of Linq, more so Linq query expressions versus the Linq methods. Don't know what I mean? Expression: var result = from knowledge in Sean select knowledge.Linq; As opposed to: var result = Sean.Select(knowledge =&#62; knowledge.Linq); Personally I would replace the lambda expression with [...]]]></description>
			<content:encoded><![CDATA[<p>So a couple of posts I read recently have been about readability of Linq, more so Linq query expressions versus the Linq methods.  Don't know what I mean?</p>
<p>Expression:</p>
<pre><span style="color: #0000ff;">var</span> result = <span style="color: #0000ff;">from</span> knowledge <span style="color: #0000ff;">in</span> Sean
             <span style="color: #0000ff;">select</span> knowledge.Linq;</pre>
<p>As opposed to:</p>
<pre><span style="color: #0000ff;">var</span> result = Sean.Select(knowledge =&gt; knowledge.Linq);</pre>
<p>Personally I would replace the lambda expression with a Func, but I can live with it right now. Anywho, the argument is that the first looks better than the second. I really don't see this as a looks problem, but a useage problem. Fact is, they both have their uses and you should know how to read both. Why is that? Well here's an example CAUSE I KNOW YOU WANT ONE!</p>
<p>One of my earlier posts had to do with <a title="FizzBuzz" href="http://byatool.com/?p=46">solving the FizzBuzz</a> thing with Linq where I gave you this bad ass solution:</p>
<pre> <span style="color: #0000ff;">var</span> result =
      listToConvert
      .<span style="color: #000000;">Where</span>(WhereBothDivisible(fizzNumber, buzzNumber))
      .<span style="color: #000000;">Select</span>(selectKeyValuePair(<span style="color: #ff0000;">"FizzBuzz"</span>))
      .Concat(
            listToConvert
            .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
            .Select(selectKeyValuePair(<span style="color: #ff0000;">"Buzz"</span>)))
            .Concat(
                  listToConvert
                  .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
                  .Select(selectKeyValuePair(<span style="color: #ff0000;">"Fizz"</span>)))
                  .Concat(
                         listToConvert
                        .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
                        .Select(selectKeyValuePair(<span style="color: #ff0000;">"Nothing"</span>)));</pre>
<p>As you can see, I've used both Func fields and methods to return Funcs to clean up how this would look. I'll even show what it would look like without this approach:</p>
<pre><span style="color: #0000ff;">var</span> result = listToConvert.Where(currentItem =&gt;
             IsDivisible(currentItem, fizzNumber) &amp;&amp; IsDivisible(currentItem, buzzNumber)
             ).Select(currentItem =&gt; new KeyValuePair(currentItem, <span style="color: #ff0000;">"FizzBuzz"</span>)).Concat(...</pre>
<p>Now I can totally admit that this second one I am showing is just ouch. So the first lesson to be learn is that Funcs and Methods that return Funcs can significantly clean up the Linq Method approach.</p>
<p>Now you could do the same with expressions:</p>
<pre> <span style="color: #0000ff;">var</span> fizzBuzz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
                <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
                <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"FizzBuzz"</span>);

 <span style="color: #0000ff;">var</span> buzz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
            <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
            <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Buzz"</span>);

 <span style="color: #0000ff;">var</span> fizz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
            <span style="color: #0000ff;">where</span> WhereFizzDivisable(fizzNumber, buzzNumber)
            <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Fizz"</span>);

<span style="color: #0000ff;">var</span> neither = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
              <span style="color: #0000ff;">where</span> WhereNeitherDivisable(fizzNumber, buzzNumber)
              <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Fizz"</span>);</pre>
<p>Ok so nice and pretty, but now what? Concatenation. This is where is gets ugly:</p>
<pre>  fizzBuzz.Concat(fizz.Concat(buzz.Concat(neither))));</pre>
<p>OR</p>
<pre> <span style="color: #0000ff;">var</span> fizzBuzz = <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
                <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
                <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"FizzBuzz"</span>)
                .Concat(
                     <span style="color: #0000ff;">from</span> currentNumber <span style="color: #0000ff;">in</span> listToConvert
                     <span style="color: #0000ff;">where</span> WhereBuzzDivisable(fizzNumber, buzzNumber)
                     <span style="color: #0000ff;">select</span> selectKeyValuePair(<span style="color: #ff0000;">"Buzz"</span>))
                     .Concat(....);</pre>
<p>See what I'm getting at? The non expression one is looking a bit better now or maybe this is a fight to see which is less fugly. Now I admit that this may not be the best FizzBuzz solution, but it gives an example or where the Linq queries can go very wrong.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/general-coding/fizzbuzz-with-linq-extension-methods/" title="Solve FizzBuzz Using Linq Extension Methods">Solve FizzBuzz Using Linq Extension Methods</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/what-is-readable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamic Linq: OrderBy Using a String for a Property Name</title>
		<link>http://byatool.com/general-coding/orderby-using-a-property-name/</link>
		<comments>http://byatool.com/general-coding/orderby-using-a-property-name/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 13:39:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Order By]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/10/01/orderby-using-a-property-name/</guid>
		<description><![CDATA[Now this is kind of dangerous to do since there is no compile time check (Like most things set in markup) but say you want to sort a collection, using the Linq extension methods, but you don't know what you what to sort on at any given time. On top of that, you have a [...]]]></description>
			<content:encoded><![CDATA[<p>Now this is kind of dangerous to do since there is no compile time check (Like most things set in markup) but say you want to sort a collection, using the Linq extension methods, but you don't know what you what to sort on at any given time. On top of that, you have a datagrid and a bunch of sort expressions to deal with. Now you could do something like create a hashtable full of lambda expressions that the key is the sort expression:</p>
<pre><span style="color: #00cccc;">Dictionary</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">IComparable</span>&gt;&gt; list;

userList = <span style="color: #00cccc;">User</span>.GetUserList();
list = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">Dictionary</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">IComparable</span>&gt;&gt;();
list.Add(<span style="color: #990000;">"UserName"</span>, currentUser =&gt; currentUser.UserName);
list.Add(<span style="color: #990000;">"UserID"</span>, currentUser =&gt; currentUser.UserID);
userList.OrderBy(list[<span style="color: #990000;">"UserID"</span>]);</pre>
<p>Works just fine, and might be preferable to what I'm about to show. OooOoOO sound eerie?</p>
<pre><span style="color: #009900;">//This is just to get the property info using reflection.  In order to get the value</span>
<span style="color: #009900;">//from a property dynamically, we need the property info from the class</span>
<span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">PropertyInfo</span>[] GetInfo&lt;K&gt;(K item) <span style="color: #3333ff;">where</span> K : <span style="color: #3333ff;">class</span>
{
  <span style="color: #00cccc;">PropertyInfo</span>[] propertyList;
  <span style="color: #00cccc;">Type</span> typeInfo;

  typeInfo = item.GetType();
  propertyList = typeInfo.GetProperties();

  <span style="color: #3333ff;">return</span> propertyList;
}

<span style="color: #009900;">//This is the dynamic order by func that the OrderBy method needs to work</span>
<span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">IComparable</span> OrderByProperty&lt;T&gt;(<span style="color: #00cccc;">String</span> propertyName, T item)
  <span style="color: #3333ff;">where</span> T : <span style="color: #3333ff;">class</span>
{
  <span style="color: #00cccc;">PropertyInfo</span>[] propertyList;

  propertyList = GetInfo(item);

  <span style="color: #009900;">//Here we get the value of that property of the passed in item and make sure</span>
  <span style="color: #009900;">//to type the object (Which is what GetValue returns) into an IComparable</span>
  return (<span style="color: #00cccc;">IComparable</span>)propertyList.First(currentProperty
    =&gt; currentProperty.Name == propertyName).GetValue(item, <span style="color: #3333ff;">null</span>);
}</pre>
<p>And use:</p>
<pre><span style="color: #009900;">//This takes the current user and calls the OrderByProperty method which in turn</span>
<span style="color: #009900;">//gives us the Func OrderBy is requesting.</span>
<span style="color: #3333ff;">var</span> test = userList.OrderBy(currentUser
  =&gt; DynamicPropertySort.OrderByProperty(<span style="color: #990000;">"UserID"</span>, currentUser)).ToList();</pre>
<p>Ok so what the hell? I mean intellisense on the OrderBy method doesn't give much help. <span style="color: #00cccc;">Func</span>&lt;&lt;<span style="color: #00cccc;">User</span>, TKey&gt;&gt;. Yeah ok. So basically the return type is open. Well this kind of sucks right? Because I would have to return a Func that already knows the return type. (Be it string, int, ect) Of course, this would mean we would have to handle each sort expression in code. NOT VERY DYNAMIC IS IT? Well f that. Truth is, what the order by is looking for is a Func that takes in a User and returns something it can compare. This is where <span style="color: #00cccc;">IComparable </span>comes in.</p>
<p>The OrderBy has to take the returned value, say UserID which is an int, and figure out how to compare it to another value. Pretty simple. So as long as the property you are ordering by uses <span style="color: #00cccc;">IComparable</span>, you're good to go. Pretty nice huh?</p>
<p>Now I would suggest, if you use this (HAHAHAHA), is to cache a dictionary of the property info with the class type as the key so that you don't have to use as much reflection everytime. I just didn't put that in.</p>
<p>U U USING</p>
<pre><span style="color: #3333ff;">using</span> System;
<span style="color: #3333ff;">using</span> System.Collections.Generic;
<span style="color: #3333ff;">using</span> System.Linq;
<span style="color: #3333ff;">using</span> System.Reflection;
<span style="color: #3333ff;">using</span> System.Text;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/when-is-a-field-not-a-field/" title="When is a field not a field?">When is a field not a field?</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/general-coding/adding-to-the-select/" title="Adding to the Select">Adding to the Select</a></li><li><a href="http://byatool.com/general-coding/im-starting-to-worry-about-myself/" title="I&#8217;m starting to worry about myself">I&#8217;m starting to worry about myself</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/orderby-using-a-property-name/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Fun With Linq</title>
		<link>http://byatool.com/general-coding/more-fun-with-linq/</link>
		<comments>http://byatool.com/general-coding/more-fun-with-linq/#comments</comments>
		<pubDate>Tue, 30 Sep 2008 13:46:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/09/30/more-fun-with-linq/</guid>
		<description><![CDATA[Say you have a class named BannedProgram and it has a collection of DayOfWeek and a string ProcessName. Now the collection of DayOfWeek is basically a way to set the days of the week it's banned. With this you want to create a collection of these BannedPrograms, each with their own names and days they [...]]]></description>
			<content:encoded><![CDATA[<p>Say you have a class named BannedProgram and it has a collection of DayOfWeek and a string ProcessName. Now the collection of DayOfWeek is basically a way to set the days of the week it's banned. With this you want to create a collection of these BannedPrograms, each with their own names and days they are banned. Simple, I know.</p>
<p>Next you have a list of processes that are currently running and you want to get all the processes that match the names in the BannedPrograms list AND if the current day is a banned day.</p>
<p>First you need the day checked function:</p>
<pre>
<span style="color: #3333ff;">private</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">DayOfWeek</span>, <span style="color: #00cccc;">Boolean</span>&gt; dayIsToday =
  currentDay =&gt; currentDay == DateTime.Now.DayOfWeek;</pre>
<p>Then you need the method to get the banned processes that are currently running:</p>
<pre>
<span style="color: #3333ff;">private</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Process</span>[] GetBannedProcesses(<span style="color: #00cccc;">BannedProgram</span>[] programs, <span style="color: #00cccc;">Process</span>[] processes)
{
  <span style="color: #3333ff;">var</span> processList = <span style="color: #3333ff;">from</span> process <span style="color: #3333ff;">in</span> processes
  <span style="color: #3333ff;">where</span>
  (
    <span style="color: #3333ff;">from</span> program <span style="color: #3333ff;">in</span> programs
    <span style="color: #3333ff;">where</span> program.DaysBanned.Any(dayIsToday)
    <span style="color: #3333ff;">select</span> program.ProcessName
  ).Contains(process.ProcessName)
  <span style="color: #3333ff;">select</span> process;

  <span style="color: #3333ff;">return</span> processList.ToArray();
}</pre>
<p>What this is doing:</p>
<p>Well if you look at this:</p>
<pre><span style="color: #3333ff;">from</span> program <span style="color: #3333ff;">in</span> programs
<span style="color: #3333ff;">where</span> program.DaysBanned.Any(dayIsToday)
<span style="color: #3333ff;">select</span> program.ProcessName</pre>
<p>This is going to grab any BannedProgram that has a DayOfWeek that matches today and it will select only it's name. This will give you a list of names of the BannedProcesses that can not be played today.</p>
<pre><span style="color: #3333ff;">var</span> processList = <span style="color: #3333ff;">from</span> process <span style="color: #3333ff;">in</span> processes
<span style="color: #3333ff;">where</span>
(
  <span style="color: #3333ff;">from</span> program <span style="color: #3333ff;">in</span> programs
  <span style="color: #3333ff;">where</span> program.DaysBanned.Any(dayIsToday)
  <span style="color: #3333ff;">select</span> program.ProcessName
).Contains(process.ProcessName)</pre>
<p>This checks to see if any of the currently running processes have a name that matches a name in the banned program list.</p>
<p>And now you have a list of processes to kill. Yay. Not sure this is a big deal, just thought it was a fun example of using linq and subselects.</p>
<p>USING???</p>
<pre><span style="color: #3333ff;">using</span> System;
<span style="color: #3333ff;">using</span> System.Diagnostics;
<span style="color: #3333ff;">using</span> System.Linq;
<span style="color: #3333ff;">using</span> System.ServiceProcess;
<span style="color: #3333ff;">using</span> System.Windows.Forms;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/more-fun-with-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More Useless info</title>
		<link>http://byatool.com/general-coding/more-useless-info/</link>
		<comments>http://byatool.com/general-coding/more-useless-info/#comments</comments>
		<pubDate>Tue, 30 Sep 2008 13:21:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Windows Service]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/09/30/more-useless-info/</guid>
		<description><![CDATA[Just in case you wanted to create something to kill a process, I have this little bit: using System; using System.Diagnostics; Action&#60;Process&#62; killProcess = currentProcess =&#62; currentProcess.Kill(); Process[] processes; String processToKill; processToKill = "WAR"; processes = Process.GetProcesses(); processes.Select(currentProcess =&#62; currentProcess.ProcessName == processToKill) .ToList() .ForEach(killProcess); I originally intended this as a service that would kill processes [...]]]></description>
			<content:encoded><![CDATA[<p>Just in case you wanted to create something to kill a process, I have this little bit:</p>
<pre><span style="color: #3333ff;">using</span> System;
<span style="color: #3333ff;">using</span> System.Diagnostics;

<span style="color: #00cccc;">Action</span>&lt;<span style="color: #00cccc;">Process</span>&gt; killProcess = currentProcess =&gt; currentProcess.Kill();
<span style="color: #00cccc;">Process</span>[] processes;
<span style="color: #00cccc;">String</span> processToKill;

processToKill = <span style="color: #990000;">"WAR"</span>;
processes = Process.GetProcesses();

processes.Select(currentProcess =&gt; currentProcess.ProcessName == processToKill)
.ToList()
.ForEach(killProcess);</pre>
<p>I originally intended this as a service that would kill processes that were running on a specific day. IE To stop myself from playing games during the week. Problem was finding a way to stop me from killing the service. Now you can set a service to disallowing stopping it. The idea being that I would have another program that would stop it only if a password was enter correctly. (A certain woman would have this password) Trouble is, I can just open up the task manager and kill the process. Now I have to rely on self control. WHICH IS THE REASON WHY I WANTED THIS IN THE FIRST PLACE.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/add-on/random-add-on-automapper/" title="Random Add-On &#8211; Automapper">Random Add-On &#8211; Automapper</a></li><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/more-useless-info/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Combine Lambda Expressions: The And and the Or</title>
		<link>http://byatool.com/general-coding/combining-lambda-expressions/</link>
		<comments>http://byatool.com/general-coding/combining-lambda-expressions/#comments</comments>
		<pubDate>Tue, 09 Sep 2008 20:17:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Expression]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/09/09/combining-lambda-expressions/</guid>
		<description><![CDATA[Found this post here but wanted to make a really simple example to demonstrate this. The idea is simple, take something like this: currentItem =&#62; currentItem.BooleanMethodOne() &#38;&#38; currentItem.BooleanMethodTwo() but say you only want to have one clause or both. Well you could make three separate expressions, but what if you wanted to add even more [...]]]></description>
			<content:encoded><![CDATA[<p>Found this post <a href="http://www.albahari.com/nutshell/predicatebuilder.html">here</a> but wanted to make a really simple example to demonstrate this.</p>
<p>The idea is simple, take something like this:</p>
<pre>currentItem =&gt; currentItem.BooleanMethodOne() &amp;&amp; currentItem.BooleanMethodTwo()</pre>
<p>but say you only want to have one clause or both. Well you could make three separate expressions, but what if you wanted to add even more later? What if you wanted to mix and match? What if you're reading thing because you watched to see what page could possibly be on the last page of a google search? Well I have answers... stolen answers.</p>
<p>First the needed And and Or methods:</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt; And&lt;T&gt;(
<span style="color: #00cccc;">   Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt; expressionOne,
<span style="color: #00cccc;">    Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt; expressionTwo
)
{
<span style="color: #009900;">  //Basically this is like a bridge between the two expressions.  It will take the T</span>
<span style="color: #009900;">  //parameter from expressionOne and apply it to expression two. So if </span>
<span style="color: #009900;">  // oneItem =&gt; oneItem.OneMethod() is expressionOne</span>
<span style="color: #009900;">  // twoItem =&gt; twoItem.TwoMethod() is expressionTwo</span>
<span style="color: #009900;">  //it would be like replacing the twoItem with the oneItem so that they now point</span>
<span style="color: #009900;">  //to the same thing.</span>
<span style="color: #3333ff;">  var</span> invokedSecond = <span style="color: #00cccc;">Expression</span>.Invoke(expressionTwo, expressionOne.Parameters.Cast&lt;<span style="color: #00cccc;">Expression</span>&gt;());

<span style="color: #009900;">  //Now this is to create the needed expresions to return.  It will take both early expressions</span>
<span style="color: #009900;">  //and use the item from the first expression in both.</span>
<span style="color: #009900;">                    </span>
<span style="color: #009900;">  //It will look something like this:</span>
<span style="color: #009900;">  //currentItem =&gt; (currentItem.OneMethod And Invoke(currentItem =&gt; currentItem.TwoMethod()))</span>
<span style="color: #009900;">  //As you can see, it looks to be running expressionOne and then a new method that basically</span>
<span style="color: #009900;">  //calls expressionTwo with the same value (currentItem)</span>
<span style="color: #3333ff;">  return</span> <span style="color: #00cccc;">Expression</span>.Lambda&lt;<span style="color: #00cccc;">Func</span>&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt;(<span style="color: #00cccc;">
   Expression</span>.And(expressionOne.Body, invokedSecond), expressionOne.Parameters
  );
}

<span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Expressio</span><span style="color: #00cccc;">n</span>&lt;<span style="color: #00cccc;">Func</span>&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt; Or&lt;T&gt;(<span style="color: #00cccc;">
Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt; expressionOne, <span style="color: #00cccc;">
Expression</span>&lt;<span style="color: #00cccc;">Fun</span>c&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt; expressionTwo
)
{
<span style="color: #3333ff;">  var</span> invokedSecond = <span style="color: #00cccc;">Expression</span>.Invoke(expressionTwo, expressionOne.Parameters.Cast&lt;<span style="color: #00cccc;">Expression</span>&gt;());

<span style="color: #3333ff;">  return</span> <span style="color: #00cccc;">Expression</span>.Lambda&lt;<span style="color: #00cccc;">Func</span>&lt;T, <span style="color: #00cccc;">Boolean</span>&gt;&gt;(
<span style="color: #00cccc;">   Expression</span>.Or(expressionOne.Body, invokedSecond), expressionOne.Parameters
  );
}</pre>
<p>And here's a test for it:</p>
<pre><span style="color: #3333ff;">String</span>[] list;

list = <span style="color: #3333ff;">new</span> <span style="color: #3333ff;">String</span>[] { <span style="color: #990000;">"a"</span>, <span style="color: #990000;">"b"</span>, <span style="color: #990000;">"c"</span>, <span style="color: #990000;">"ac"</span>, <span style="color: #990000;">"ab"</span>, <span style="color: #990000;">"cc"</span>, <span style="color: #990000;">"d"</span>, <span style="color: #990000;">"dd"</span>, <span style="color: #990000;">"dc"</span> };

<span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Boolean</span>&gt;&gt; stringLikeA = currentString =&gt; currentString.Contains(<span style="color: #990000;">"a"</span>);
<span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Boolean</span>&gt;&gt; stringLikeB = currentString =&gt; currentString.Contains(<span style="color: #990000;">"b"</span>);
<span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Boolean</span>&gt;&gt; stringLikeC = currentString =&gt; currentString.Contains(<span style="color: #990000;">"c"</span>);

<span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">String</span>, Boolean&gt;&gt; neededUser = And&lt;<span style="color: #00cccc;">String</span>&gt;(stringLikeA, stringLikeB);
list.Where(neededUser.Compile());

<span style="color: #009900;">//a</span>
<span style="color: #00cccc;">Assert</span>.IsTrue(list.Where(neededUser.Compile()).Count() == 1);  //ab

<span style="color: #009900;">//a, c, ac, ab, cc, dc</span>
neededUser = Or&lt;<span style="color: #00cccc;">String</span>&gt;(stringLikeA, stringLikeC);

<span style="color: #00cccc;">Assert</span>.IsTrue(list.Where(neededUser.Compile()).Count() == 6);

<span style="color: #009900;">//ab, c, ac, cc, dc</span>
neededUser = And&lt;<span style="color: #00cccc;">String</span>&gt;(stringLikeA, stringLikeB);
neededUser = Or&lt;<span style="color: #00cccc;">String</span>&gt;(neededUser, stringLikeC);
<span style="color: #00cccc;">Assert</span>.IsTrue(list.Where(neededUser.Compile()).Count() == 5);</pre>
<p>USINGS!!ONEONE</p>
<pre><span style="color: #3333ff;">using</span> System;
<span style="color: #3333ff;">using</span> System.Linq;
<span style="color: #3333ff;">using</span> System.Linq.Expressions;
<span style="color: #3333ff;">using</span> Microsoft.VisualStudio.TestTools.UnitTesting;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/combining-lambda-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Solve FizzBuzz Using Linq Extension Methods</title>
		<link>http://byatool.com/general-coding/fizzbuzz-with-linq-extension-methods/</link>
		<comments>http://byatool.com/general-coding/fizzbuzz-with-linq-extension-methods/#comments</comments>
		<pubDate>Mon, 08 Sep 2008 13:40:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Action]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[FizzBuzz]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/09/08/fizzbuzz-with-linq-extension-methods/</guid>
		<description><![CDATA[So if you haven't heard of the FizzBuzz test, it's basically taking in a list of numbers and figuring out if they are divisible, cleanly, by two numbers. Say you have 3 and 5 and this is your list: 1 3 5 10 15 If the number is divisible by 3, then return the Fizz [...]]]></description>
			<content:encoded><![CDATA[<p>So if you haven't heard of the FizzBuzz test, it's basically taking in a list of numbers and figuring out if they are divisible, cleanly, by two numbers. Say you have 3 and 5 and this is your list:</p>
<p>1</p>
<p>3</p>
<p>5</p>
<p>10</p>
<p>15</p>
<p>If the number is divisible by 3, then return the Fizz string. If the number is divisible by 5, return a Buzz string. If it's divisible by both, then return FizzBuzz.</p>
<p>1</p>
<p>Fizz</p>
<p>Buzz</p>
<p>Buzz</p>
<p>FizzBuzz</p>
<p>Pretty simple and in actuality pretty easy to do with old C# tools, but I wanted to do this with Linq. With the use of Funcs, Actions, and Linq extension methods it can be done fairly easily. Technically you can do the whole thing in one line if you don't want to bother with refactoring.</p>
<p>I have no idea how to format this cleanly, so sorry if the format is confusing. Basically it is take a list, get the ones you want, concatenate it with the next list.</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">IList</span>&lt;<span style="color: #00cccc;">KeyValuePair</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">String</span>&gt;&gt; ConvertListOfIntegersWithLinqMethods(<span style="color: #00cccc;">IList</span>&lt;<span style="color: #00cccc;">Int32</span>&gt; listToConvert, <span style="color: #00cccc;">Int32</span> fizzNumber, <span style="color: #00cccc;">Int32</span> buzzNumber)
{
<span style="color: #3333ff;">var</span> result =
  listToConvert
    .Where(WhereBothDivisible(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair(<span style="color: #cc0000;">"FizzBuzz"</span>))
    .Concat(
  listToConvert
    .Where(WhereBuzzDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair(<span style="color: #cc0000;">"Buzz"</span>)))
    .Concat(
  listToConvert
    .Where(WhereFizzDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair(<span style="color: #cc0000;">"Fizz"</span>)))
    .Concat(
  listToConvert
    .Where(WhereNeitherDivisable(fizzNumber, buzzNumber))
    .Select(selectKeyValuePair(<span style="color: #cc0000;">"Nothing"</span>)));

 return result.ToList().OrderBy(currentItem =&gt; currentItem.Key).ToList();
}</pre>
<p>Using these:</p>
<pre><span style="color: #3333ff;">private</span> <span style="color: #3333ff;">stati</span>c <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">KeyValuePair</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">String</span>&gt;&gt; selectKeyValuePair(<span style="color: #00cccc;">String</span> value)
{
 <span style="color: #3333ff;">return</span> currentItem =&gt; <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">KeyValuePair</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">String</span>&gt;(currentItem, value);
}

<span style="color: #3333ff;">private</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">Boolean</span>&gt; WhereBothDivisible(<span style="color: #00cccc;">Int32</span> fizzNumber, <span style="color: #00cccc;">Int32</span> buzzNumber)
{
 <span style="color: #3333ff;">return</span>  currentItem =&gt; IsDivisible(currentItem, fizzNumber) &amp;&amp; IsDivisible(currentItem, buzzNumber);
}

<span style="color: #3333ff;">private</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">Boolean</span>&gt; WhereFizzDivisable(<span style="color: #00cccc;">Int32</span> fizzNumber, <span style="color: #00cccc;">Int32</span> buzzNumber)
{
 <span style="color: #3333ff;">return</span> currentItem =&gt; IsDivisible(currentItem, fizzNumber) &amp;&amp; !IsDivisible(currentItem, buzzNumber);
}

<span style="color: #3333ff;">private</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">Boolean</span>&gt; WhereBuzzDivisable(<span style="color: #00cccc;">Int32</span> fizzNumber, <span style="color: #00cccc;">Int32</span> buzzNumber)
{
 <span style="color: #3333ff;">return</span> currentItem =&gt; !IsDivisible(currentItem, fizzNumber) &amp;&amp; IsDivisible(currentItem, buzzNumber);
}

<span style="color: #3333ff;"> private</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Int32</span>, <span style="color: #00cccc;">Boolean</span>&gt; WhereNeitherDivisable(<span style="color: #00cccc;">Int32</span> fizzNumber, <span style="color: #00cccc;">Int32</span> buzzNumber)
{
 <span style="color: #3333ff;">return</span> currentItem =&gt; !IsDivisible(currentItem, fizzNumber) &amp;&amp; !IsDivisible(currentItem, buzzNumber);
}</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/life-is-fun-when-you-are-slow/" title="Life is fun when you are slow">Life is fun when you are slow</a></li><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/fizzbuzz-with-linq-extension-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Beyond the wall</title>
		<link>http://byatool.com/lessons/beyond-the-wall/</link>
		<comments>http://byatool.com/lessons/beyond-the-wall/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 13:41:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/09/02/beyond-the-wall/</guid>
		<description><![CDATA[So I never gave a solution to this problem and thought I might do that real fast. If you recall, this was the main sticking point of creating a Func for a select clause: Func&#60;User, EHH??&#62; selectUserID = currentUser =&#62; new { currentUser.ID, currentUser.UserName }; Well there is no one solution to this, but there [...]]]></description>
			<content:encoded><![CDATA[<p>So I never gave a solution to<a href="http://byatool.blogspot.com/2008/08/and-then-you-hit-wall.html"> this problem</a> and thought I might do that real fast.</p>
<p>If you recall, this was the main sticking point of creating a Func for a select clause:</p>
<pre><span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">EHH??</span>&gt; selectUserID = currentUser =&gt;  <span style="color: #3333ff;">new</span> { currentUser.ID, currentUser.UserName };</pre>
<p>Well there is no one solution to this, but there is an easy and clean solution:</p>
<pre> <span style="color: #3333ff;">public</span> <span style="color: #3333ff;">class</span> UserQueryItem
 {
   <span style="color: #3333ff;">public</span> UserQueryItem ( <span style="color: #00cccc;">Int32</span> userID, <span style="color: #00cccc;">String</span> userName )
   {
      UserID = userID;
      UserName = userName;
   }

   <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">Int32</span> UserID { <span style="color: #3333ff;">get</span>; <span style="color: #3333ff;">set</span>; }
   <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">String</span> UserName { <span style="color: #3333ff;">get</span>; <span style="color: #3333ff;">set</span>; }
 }</pre>
<p>Create a class to hold the information.</p>
<pre> <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">UserQueryItem</span>&gt; selectUserID = currentUser =&gt;  <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">UserQueryItem</span> { UserID = currentUser.ID, UserName = currentUser.UserName };</pre>
<p>Or</p>
<pre>
 <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">UserQueryItem</span>&gt; selectUserID = currentUser =&gt;  <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">UserQueryItem</span> (currentUser.ID, currentUser.UserName);</pre>
<p>Pretty simple, just a little more work.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/beyond-the-wall/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>DID U NO?!?!!111</title>
		<link>http://byatool.com/lessons/did-u-no111/</link>
		<comments>http://byatool.com/lessons/did-u-no111/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 16:48:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[3.0]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Property Initializers]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/29/did-u-no111/</guid>
		<description><![CDATA[So maybe I'm slow, but it just dawned on me that: SomeClass class = new SomeClass() { SomeProperty = "" }; Is the same as: SomeClass class = new SomeClass { SomeProperty = "" }; What?? Look closely. The "new SomeClass" no longer needs the () if you are using 3.0's property initializers. Not ground [...]]]></description>
			<content:encoded><![CDATA[<p>So maybe I'm slow, but it just dawned on me that:</p>
<pre> <span style="color: #00cccc;">SomeClass</span> class = <span style="color: #3333ff;">new</span> SomeClass() { SomeProperty = <span style="color: #cc0000;">""</span> };</pre>
<p>Is the same as:</p>
<pre> <span style="color: #00cccc;">SomeClass</span> class = <span style="color: #3333ff;">new</span> SomeClass { SomeProperty = <span style="color: #cc0000;">""</span> };</pre>
<p>What?? Look closely. The "new SomeClass" no longer needs the () if you are using 3.0's property initializers. Not ground breaking, but interesting.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/writing/byatool-com-gets-a-shiny-new-tool/" title="ByATool.com gets a shiny new tool!">ByATool.com gets a shiny new tool!</a></li><li><a href="http://byatool.com/lessons/data-annotations-mvc-and-why-you-might-like-them/" title="Data Annotations, MVC, and Why You Might Like Them">Data Annotations, MVC, and Why You Might Like Them</a></li><li><a href="http://byatool.com/add-on/random-add-on-automapper/" title="Random Add-On &#8211; Automapper">Random Add-On &#8211; Automapper</a></li><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/did-u-no111/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>And now for Contravariance</title>
		<link>http://byatool.com/lessons/and-now-for-contravariance/</link>
		<comments>http://byatool.com/lessons/and-now-for-contravariance/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 12:43:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Contravariance]]></category>
		<category><![CDATA[Covariance]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/29/and-now-for-contravariance/</guid>
		<description><![CDATA[Take the classes in the last post (First, Second, Third) and assume they are exactly the same in this example. In Covariance, we learned that whatever variable to you set equal to the return of a method has to be equal in type of larger. Or in other words, it has to have equal or [...]]]></description>
			<content:encoded><![CDATA[<p>Take the classes in the last post (<span style="color: #00cccc;">First</span>, <span style="color: #00cccc;">Second</span>, <span style="color: #00cccc;">Third</span>) and assume they are exactly the same in this example.</p>
<p>In Covariance, we learned that whatever variable to you set equal to the return of a method has to be equal in type of larger. Or in other words, it has to have equal or less functionality.</p>
<pre><span style="color: #00cccc;">  Second</span> second = ReturnThird();  <span style="color: #006600;">//OK since second has less functionality</span>

<span style="color: #00cccc;">  Third</span> third = ReturnSecond(); <span style="color: #006600;">//BAD since third has more functionality</span></pre>
<p>Now I think you can guess what Contravariance is, but if you can't it's ok. Most likely you're a tool just like me. Contravariance is the movement from small to large meaning that the type must be equal to or larger than. Following the "in other words" manor, it has to have equal or more functionality.</p>
<p>Now small note before I go on, saying that it has to have more/less functionality can be somewhat dangerous. After all, <span style="color: #00cccc;">Third</span> could inherit from <span style="color: #00cccc;">Second</span> and add no functionality, but I find this is an easier way to think of it. I suppose another way of thinking of it is that with Covariance the return type has to have equal or more knowledge. Meaning, <span style="color: #00cccc;">Second</span> has full knowledge of what <span style="color: #00cccc;">First</span> is, but <span style="color: #00cccc;">Second</span> has no idea what <span style="color: #00cccc;">Third</span> is.</p>
<p>Anywho, onto some examples. Say we take the FillX methods and add something to it.</p>
<pre><span style="color: #3333ff;">  private</span> <span style="color: #3333ff;">void</span> FillFirst(<span style="color: #00cccc;">First</span> firstToFill)
  {
    firstToFill.FirstOutput = <span style="color: #cc0000;">""</span>;
  }

<span style="color: #3333ff;">  private</span> <span style="color: #3333ff;">void</span> FillSecond(<span style="color: #00cccc;">Second</span> secondToFill)
  {
    secondToFill.SecondOutput = <span style="color: #cc0000;">""</span>;
  }

<span style="color: #3333ff;">  private</span> <span style="color: #3333ff;">void</span> FillThird(<span style="color: #00cccc;">Third</span> thirdToFill)
  {
    thirdToFill.ThirdOutput = <span style="color: #cc0000;">""</span>;
  }</pre>
<p>Right off the bat you might notice that if methods allowed Covariance with parameters, you'd be in trouble. After all, if FillThird allowed parameter covariance, you could pass in a <span style="color: #00cccc;">First</span> object. What what that object do with ThirdOutPut? As things are, you would have a bad day. Lucky for you, at least if you aren't adamant about wanting Covariance in parameters, this can't happen.</p>
<p>Well shoot, I just gave away the fun of this post. Oh well, I'll keep going in case you just have more time.</p>
<pre><span style="color: #00cccc;">  Action</span>&lt;<span style="color: #00cccc;">First</span>&gt; fillFirstAction = FillFirst;
<span style="color: #006600;">  //No problems here since FillFirst expects a First</span>

<span style="color: #00cccc;">  Action</span>&lt;<span style="color: #00cccc;">Second</span>&gt; fillSecondAction = FillFirst;
<span style="color: #006600;">  //Still no problems although this may look odd.  But remember, FillFirst</span>
<span style="color: #006600;">  //just needs an object that : First, it doesn't care if the object</span>
<span style="color: #006600;">  //has more functionality than first.</span>
<span style="color: #006600;">  //</span>
<span style="color: #006600;">  //The FillFirst method uses the FirstOutput property and by inheritance</span>
<span style="color: #006600;">  //the Second being passed in has said property</span>

<span style="color: #00cccc;">  Action</span>&lt;<span style="color: #00cccc;">Second</span>&gt; fillThirdAction = FillThird;
<span style="color: #006600;">  //Not gonna happen.  The FillThird expects a third or smaller object.  Since</span>
<span style="color: #006600;">  //Third : Second, third is smaller than second.  Implications?  Look in the </span>
<span style="color: #006600;">  //FillThirdMethod</span>
<span style="color: #006600;">  //</span>
<span style="color: #006600;">  //The method expects the object to have the ThirdOutput property which means</span>
<span style="color: #006600;">  //Second has to inherit from Third.  We know this to be untrue.</span></pre>
<p>So basically Contravariance is used with parameters in methods to guarantee the object being passed in has at least the functionality used within the method.</p>
<p>Apparently there was a problem in the lobby so there will be no refreshments served tonight.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/and-now-for-contravariance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Covariance versus Contravariance</title>
		<link>http://byatool.com/lessons/covariance-versus-contravariance/</link>
		<comments>http://byatool.com/lessons/covariance-versus-contravariance/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 18:26:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Covariance]]></category>
		<category><![CDATA[Func]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/28/covariance-versus-contravariance/</guid>
		<description><![CDATA[Ok so I stumbled on to this subject the other day and thought it was worth noting. Take these simple classes: public class First { public String FirstOutput { get; set; } } public class Second : First { public String SecondOutput { get; set; } } public class Third : Second { public String [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so I stumbled on to this subject the other day and thought it was worth noting. Take these simple classes:</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #3333ff;">class</span> <span style="color: #00cccc;">First</span>
{
  <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">String</span> FirstOutput { <span style="color: #3333ff;">get</span>; <span style="color: #3333ff;">set</span>; }
}

<span style="color: #3333ff;">public</span> <span style="color: #3333ff;">class</span> <span style="color: #00cccc;">Second</span> : <span style="color: #00cccc;">First</span>
{
  <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">String</span> SecondOutput { <span style="color: #3366ff;">get</span>; <span style="color: #3366ff;">set</span>; }
}

<span style="color: #3333ff;">public</span> <span style="color: #3333ff;">class</span> <span style="color: #00cccc;">Third</span> : <span style="color: #00cccc;">Second</span>
{
  <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">String</span> ThirdOutput { <span style="color: #3333ff;">get</span>; <span style="color: #3333ff;">set</span>; }
}</pre>
<p>So from this you can see that <span style="color: #00cccc;">Third</span> inherits <span style="color: #00cccc;">Second</span> which in turns inherits <span style="color: #00cccc;">First</span>. By terminology this would mean that <span style="color: #00cccc;">Third</span> is "smaller" than <span style="color: #00cccc;">Second</span> and <span style="color: #00cccc;">First</span> is "larger" than both. Here's an example of Covariance:</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #3333ff;">class</span> <span style="color: #00cccc;">Covariance</span>
{
  <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">Covariance</span>()
  {

      <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">First</span>&gt; returnFirstFunc = ReturnFirst;
      <span style="color: #009900;">//This works since the Func has a return type of First</span>

      <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Second</span>&gt; returnSecondFunc = ReturnThird;
      <span style="color: #00cccc;">Second</span> secondTest = returnSecondFunc();
      secondTest.FirstOutput = <span style="color: #990000;">"First"</span>;
      secondTest.SecondOutput = <span style="color: #990000;">"First"</span>;
      <span style="color: #006600;">//This works since the Func has a return type of Third which is smaller</span>
<span style="color: #006600;">       //that Second.  Therefore anyone using this Func will expect a Second to</span>
<span style="color: #006600;">       //be returned and will only use the methods/properties that a Second object</span>
<span style="color: #006600;">       //would have.  Methods/Properties that Third has by inheritance.</span>

      <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Third</span>&gt; returnThirdFunc = ReturnSecond;
      <span style="color: #006600;">//THIS WILL NOT WORK</span>
<span style="color: #006600;">       //Due to Covariance, the return of the method must be equal or smaller</span>
<span style="color: #006600;">       //that the expected type.  returnThirdFunc expects a Third or smaller object</span>
<span style="color: #006600;">       //but the ReturnSecond method returns a Second which is not smaller than Third.</span>
<span style="color: #006600;">       //Afterall, Third : Second</span>
<span style="color: #006600;">       //</span>
<span style="color: #006600;">       //Third thirdTest = returnThirdFunc();</span>
<span style="color: #006600;">       //Is the same as:</span>
<span style="color: #006600;">       //Third thirdTest = new Second();</span>
  }

  <span style="color: #3333ff;">private</span> <span style="color: #00cccc;">First</span> ReturnFirst()
  {
      <span style="color: #3333ff;">return</span> <span style="color: #3333ff;">new</span> First();
  }

  <span style="color: #3333ff;">private</span> <span style="color: #00cccc;">Second</span> ReturnSecond()
  {
      <span style="color: #3333ff;">return</span> <span style="color: #3333ff;">new</span> Second();
  }

  <span style="color: #3333ff;">private</span> <span style="color: #00cccc;">Third</span> ReturnThird()
  {
      <span style="color: #3333ff;">return</span> <span style="color: #3333ff;">new</span> Third();
  }
}</pre>
<p>Basically what this all means is that with return types, the return type must be smaller or equal to the field it's being set to. When you are dealing with Funcs, the return type must be smaller or equal to the return type for the method it's being set it. Why is that? Well think of it like this:</p>
<p>It's your first day on the job and some guy tells you to write something with whatever returnFirstFunc() returns. Now you have no way to look at the code, so you can only know that it returns <span style="color: #00cccc;">First</span>. For all you know, it could return <span style="color: #00cccc;">First</span>, <span style="color: #00cccc;">Second</span>, or <span style="color: #00cccc;">Third</span>. So you would do this:</p>
<pre><span style="color: #00cccc;">First</span> someFirst;

someFirst = returnFirstFunc();  <span style="color: #006600;">//Could return anything smaller than First</span>
someFirst.FirstOutput;  <span style="color: #006600;">//Completely legal and safe</span></pre>
<p>But would you do this?</p>
<pre>someFirst.ThirdOutput;</pre>
<p>Of course not since you only can assume it is a <span style="color: #00cccc;">First</span>. Now let's do this in reverse. Say from the above example you were allowed to do this:</p>
<pre><span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Third</span>&gt; returnThirdFunc = ReturnSecond;</pre>
<p>Could you do this?</p>
<pre><span style="color: #00cccc;">Third</span> third;

third = returnThirdFunc();
third.ThirdOutput;</pre>
<p>Yeah you can't since the <span style="color: #00cccc;">Second</span> type doesn't have the ThirdOutput property.</p>
<p>In short Covariance is the allowance of Smaller types or equal. If a method returns back Third, then you can use that method for anything that is <span style="color: #00cccc;">Third</span> or Smaller (<span style="color: #00cccc;">Second</span>, <span style="color: #00cccc;">First</span>, <span style="color: #00cccc;">Object</span>) but not for something Larger (<span style="color: #00cccc;">Fourth</span>, <span style="color: #00cccc;">Fifth</span>, ect).</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/covariance-versus-contravariance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>And then you hit the wall.</title>
		<link>http://byatool.com/lessons/and-then-you-hit-the-wall/</link>
		<comments>http://byatool.com/lessons/and-then-you-hit-the-wall/#comments</comments>
		<pubDate>Tue, 26 Aug 2008 20:39:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Anonymous Types]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Mumble Types]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/26/and-then-you-hit-the-wall/</guid>
		<description><![CDATA[So as this dynamic nonsense continues, there is a sticking point to how much fun I can have. The wall? Anonymous types and generic declarations. Here's the old: Func&#60;User, Int32&#62; selectUserID = currentUser =&#62; currentUser.UserID; Great if I want to select userIDs, but what if I want UserIDs AND UserNames... Easy right? userList.Select(currentUser =&#62; new [...]]]></description>
			<content:encoded><![CDATA[<p>So as this dynamic nonsense continues, there is a sticking point to how much fun I can have. The wall? Anonymous types and generic declarations.</p>
<p>Here's the old:</p>
<pre>  <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Int32</span>&gt; selectUserID = currentUser =&gt; currentUser.UserID;</pre>
<p>Great if I want to select userIDs, but what if I want UserIDs AND UserNames... Easy right?</p>
<pre> userList.Select(currentUser =&gt; new { currentUser.ID, currentUser.UserName });</pre>
<p>Now this is the old way, but I want the new way... IE the Func way. Problem is here</p>
<pre>  <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">EHH??</span>&gt; selectUserID = currentUser =&gt;  new { currentUser.ID, currentUser.UserName };</pre>
<p>You see, there's a problem. What the hell do I put at the return type? Fact is, without creating a method that passes back a Func or a class that has UserName and UserID properties, I'm screwed. Now from what I read <a href="http://www.interact-sw.co.uk/iangblog/2008/03/17/lambda-inference">here </a>I think I get it. First take the func:</p>
<pre>  <span style="color: #00cccc;">Func</span>&lt;K, T&gt;</pre>
<p>I have K and T that the compiler has to figure out what they are. Well it's safe to say in the example User is K, but what is T? Well it has to figure that out from the Lamdba expression. The lambda expression has no idea what it is because it's an anonymous type. So why not just use var?</p>
<pre>  <span style="color: #33ccff;">Func</span>&lt;<span style="color: #33ccff;">User</span>, <span style="color: #3333ff;">var</span>&gt;</pre>
<p>Seems easy enough. I don't have to know the type because of var right? Wellll problem is the compiler is looking at the lambda expression to figure out what var will be. Mr. Lambda expression can't really figure out the type either. Enter the wall. Currently there is no way around this without methods or classes created. Supposedly there are things called Mumble Types on the way that will solve this problem.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/when-is-a-field-not-a-field/" title="When is a field not a field?">When is a field not a field?</a></li><li><a href="http://byatool.com/general-coding/adding-to-the-select/" title="Adding to the Select">Adding to the Select</a></li><li><a href="http://byatool.com/general-coding/linq-query-versus-just-a-select/" title="Linq query versus just a Select">Linq query versus just a Select</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/and-then-you-hit-the-wall/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When is a field not a field?</title>
		<link>http://byatool.com/general-coding/when-is-a-field-not-a-field/</link>
		<comments>http://byatool.com/general-coding/when-is-a-field-not-a-field/#comments</comments>
		<pubDate>Tue, 26 Aug 2008 12:18:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Order By]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/26/when-is-a-field-not-a-field/</guid>
		<description><![CDATA[Ok so for the last few things I've been showing a more dynamic approach to linq queries , mostly dealing with collections rather than say linq to sql. Now take the new method: public List&#60;K&#62; SelectFromUserList&#60;K, L&#62;(Func&#60;User, K&#62; selectMethod, Func&#60;User, L&#62; orderBy, List&#60;User&#62; userList) { List&#60;K&#62; userList = new List&#60;K&#62;(); userList = userList.OrderBy(orderBy).Select(selectMethod).ToList(); return userList; [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so for the last few things I've been showing a more dynamic approach to linq queries , mostly dealing with collections rather than say linq to sql. Now take the new method:</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #00cccc;">List</span>&lt;K&gt; SelectFromUserList&lt;K, L&gt;(<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, K&gt; selectMethod, <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, L&gt; orderBy, <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt; userList)
{
<span style="color: #00cccc;">    List</span>&lt;K&gt; userList = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">List</span>&lt;K&gt;();
    userList = userList.OrderBy(orderBy).Select(selectMethod).ToList();

<span style="color: #3333ff;">    return</span> userList;
}</pre>
<p>and the call was this:</p>
<pre><span style="color: #00cccc;">  List</span>&lt;<span style="color: #00cccc;">String</span>&gt; newList = userList.Select(selectUser =&gt; selectUser.Name, orderUser =&gt; orderUser.ID, userList);</pre>
<p>Let's say you have two needs, selecting all the userNames and all the IDs. You could go ahead and call that method twice and inserting the lambda expressions. But let's say you want to be able to mix and match things. Say select user names and order by user id or maybe select user names and order by use names. Well there's a solution to avoid rewriting the lambda expressions:</p>
<pre><span style="color: #00cccc;">  Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Int32</span>&gt; selectUserID = currentUser =&gt; currentUser.UserID;
<span style="color: #00cccc;">  Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">String</span>&gt;selectUserName = currentUser =&gt; currentUser.UserName;

<span style="color: #00cccc;">  Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Int32</span>&gt; orderByUserID = currentUser =&gt; currentUser.UserID;
<span style="color: #00cccc;">  Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">String</span>&gt; orderByUserName = currentUser =&gt; currentUser.UserName;</pre>
<p>What the? See a while ago I had a method to pass back the expression, but in this case there's nothing to create the expression from (a passed in parameter) since they are really simple expressions. How would I use them?</p>
<pre>
<span style="color: #00cccc;">  List</span>&lt;<span style="color: #00cccc;">Int32</span>&gt; userIDs;
<span style="color: #00cccc;">  List</span>&lt;<span style="color: #00cccc;">User</span>&gt; userList;
<span style="color: #00cccc;">  List</span>&lt;<span style="color: #00cccc;">String</span>&gt; userNames;
  userIDs = SelectFromUserList(selectUserID, orderByUserID, userList);
  userNames = SelectFromUserList(selectUserName, orderByUserID, userList);</pre>
<p>Pretty nice huh?</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/orderby-using-a-property-name/" title="Dynamic Linq: OrderBy Using a String for a Property Name">Dynamic Linq: OrderBy Using a String for a Property Name</a></li><li><a href="http://byatool.com/general-coding/adding-to-the-select/" title="Adding to the Select">Adding to the Select</a></li><li><a href="http://byatool.com/c/i-are-tupid/" title="I are tupid">I are tupid</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/when-is-a-field-not-a-field/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding to the Select</title>
		<link>http://byatool.com/general-coding/adding-to-the-select/</link>
		<comments>http://byatool.com/general-coding/adding-to-the-select/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 12:37:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Order By]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/25/adding-to-the-select/</guid>
		<description><![CDATA[So in the last post there was something like this: public List&#60;K&#62; SelectUserNameList&#60;K&#62;(Func&#60;User, K&#62; selectMethod, List&#60;User&#62; userList) { return userList.Select(selectMethod, userList).ToList(); } Called by this: List&#60;String&#62; newList = userList.Select(user =&#62; user.Name, userList); Ok so what if you want to order something? Well same idea, just another Func. But remember, a Func that can order by [...]]]></description>
			<content:encoded><![CDATA[<p>So in the last post there was something like this:</p>
<pre> <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">List</span>&lt;K&gt; SelectUserNameList&lt;K&gt;(<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, K&gt; selectMethod, <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt; userList)
 {
   return userList.Select(selectMethod, userList).ToList();
 }</pre>
<p>Called by this:</p>
<pre> <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">String</span>&gt; newList = userList.Select(user =&gt; user.Name, userList);</pre>
<p>Ok so what if you want to order something? Well same idea, just another Func. But remember, a Func that can order by any type. If you look at the OrderBy method, it expects a <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, L&gt; where L is just some type you are returning. If you were ordering by UserID, well that would be an integer. Problem is, like select, you don't want to be held down by a specific type.</p>
<pre> <span style="color: #3333ff;">public</span> <span style="color: #00cccc;">List</span>&lt;K&gt; SelectFromUserList&lt;K, L&gt;(<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, K&gt; selectMethod, <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, L&gt; orderBy, <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt; userList)
 {
   <span style="color: #00cccc;">List</span>&lt;K&gt; userList = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">List</span>&lt;K&gt;();

   userList = userList.OrderBy(orderBy).Select(selectMethod).ToList();

   <span style="color: #3333ff;">return</span> userList;
 }</pre>
<p>And the new call would be:</p>
<pre> <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">String</span>&gt; newList = userList.Select(selectUser =&gt; selectUser.Name, orderUser =&gt; orderUser.ID, userList);</pre>
<p>Now something of note is the order in which you call the methods. Remember, x.OrderBy().Select() is saying take collection X, order it by L and create a new collection of X, then select whatever you want. You can not do the reverse. Say you want to select a list of UserNames ordered by UserName. Well you can either:</p>
<p>1) Order the list by user name in a list of users then select the user names.</p>
<p>2) Select a list of user names into a list of strings, order that list by a string.</p>
<p>What if you want to select user names but order by user id? You can:</p>
<p>1) Order the list by user id and create a list of users then select the user names.</p>
<p>2) Select a list of user names into a list of string and... eh LOSE</p>
<p>Best part about:</p>
<pre> userList = userList.Select(selectMethod).OrderBy(orderBy).ToList();</pre>
<p>Is that the error is somewhat misleading. It gives you the "Cannot be inferred by usage" error, not the "Idiot, you can't order a list of Strings by UserID". So you have to be careful on how you have things in order.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/when-is-a-field-not-a-field/" title="When is a field not a field?">When is a field not a field?</a></li><li><a href="http://byatool.com/c/i-are-tupid/" title="I are tupid">I are tupid</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/orderby-using-a-property-name/" title="Dynamic Linq: OrderBy Using a String for a Property Name">Dynamic Linq: OrderBy Using a String for a Property Name</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/adding-to-the-select/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Speaking of Select</title>
		<link>http://byatool.com/general-coding/speaking-of-select/</link>
		<comments>http://byatool.com/general-coding/speaking-of-select/#comments</comments>
		<pubDate>Fri, 22 Aug 2008 17:46:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Like]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/22/speaking-of-select/</guid>
		<description><![CDATA[So like Where and other fine Extension methods, Select allows you to either give it a lambda expression like so: List&#60;String&#62; newList = userList.Select(user =&#62; user.Name); Or List&#60;Int32&#62; newList = userList.Select(user =&#62; user.ID); So either you get a list of Names or IDs. What the hell do you care? Well if you are capable of [...]]]></description>
			<content:encoded><![CDATA[<p>So like Where and other fine Extension methods, Select allows you to either give it a lambda expression like so:</p>
<pre>  <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">String</span>&gt; newList = userList.Select(user =&gt; user.Name);</pre>
<p>Or</p>
<pre><span style="color: #00cccc;">  List</span>&lt;<span style="color: #00cccc;">Int32</span>&gt; newList = userList.Select(user =&gt; user.ID);</pre>
<p>So either you get a list of Names or IDs. What the hell do you care? Well if you are capable of breathing, you should also notice that one list is a list of strings the other a list of integers. What if you wanted a generic select method? Well for starters you would do something like this:</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">String</span>&gt; SelectFromUserList(<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">String</span>&gt; selectMethod, <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt; userList)
{
<span style="color: #3333ff;">  return</span> userList.Select(selectMethod).ToList();
}</pre>
<p>Where the select method for a user name would be something like this:</p>
<pre><span style="color: #00cccc;">  List</span>&lt;<span style="color: #00cccc;">String</span>&gt; nameList = SelectFromUserList(currentUser =&gt; currentUser.UserName, userList);</pre>
<p>Sweet... oh wait, that only works if I want a list strings. Great if I wanted LastName, FirstName, ect but sucks if I wanted an integer ID.</p>
<pre><span style="color: #00cccc;">  List</span>&lt;<span style="color: #00cccc;">String</span>&gt; nameList = SelectFromUserList(currentUser =&gt; currentUser.UserID, userList); <span style="color: #009900;">//BOOM</span></pre>
<p>But wait, you can do that!</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #00cccc;">List</span>&lt;K&gt; SelectUserNameList&lt;K&gt;(<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, K&gt; selectMethod, <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt; userList)
{
<span style="color: #3333ff;">  return</span> userList.Select(selectMethod).ToList();
}</pre>
<p>Aw snap, now I can get a list of anything I want, well at least a one type, one dimensional array. By the way, this is the first step in probably a series of posts that will end up with a much cleaner way of doing this.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/the-switch-remover/" title="The Switch Remover: Convert Switch Statements to Dictionaries">The Switch Remover: Convert Switch Statements to Dictionaries</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/speaking-of-select/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linq query versus just a Select</title>
		<link>http://byatool.com/general-coding/linq-query-versus-just-a-select/</link>
		<comments>http://byatool.com/general-coding/linq-query-versus-just-a-select/#comments</comments>
		<pubDate>Fri, 22 Aug 2008 14:07:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/22/linq-query-versus-just-a-select/</guid>
		<description><![CDATA[Something I ran into using the Ajax.dll and AjaxMethods (Or basically the idea of being able to call a method from .cs file in javascript) is that when returning a list of Users there was difficulty in serialization. Basically, if you have a list of users that contain a list of roles that contain a [...]]]></description>
			<content:encoded><![CDATA[<p>Something I ran into using the Ajax.dll and AjaxMethods (Or basically the idea of being able to call a method from .cs file in javascript) is that when returning a list of Users there was difficulty in serialization. Basically, if you have a list of users that contain a list of roles that contain a list of permissions that contain seven wives with seven children with seven dogs and seven cats... Basically a lot of information. Now lazy loading should take care of this, but lets assume there is no lazy loading.(No idea what would cause that...) Well you have an awful lot to pushout to the front end. Let's just say it can be a little sluggish. Lets assume you are just sending the list out, and you've already done all the querying.</p>
<p>You could do:</p>
<pre> <span style="color: #3333ff;">return</span> userList;</pre>
<p>Which is what I was doing. Kind of slow.</p>
<p>You could do:</p>
<pre> <span style="color: #3333ff;">var</span> query = <span style="color: #3333ff;">from</span> user <span style="color: #3333ff;">in</span> userList
             <span style="color: #3333ff;">select</span> <span style="color: #3333ff;">new</span>
             {
                UserName = user.UserName,
                UserID = user.ID
             };

 <span style="color: #3333ff;">return</span> query.ToList();</pre>
<p>Nothing wrong with that, just a bit verbose for something so simple.</p>
<p>You could do this:</p>
<pre> <span style="color: #3333ff;">return</span> userList.Select(currentItem =&gt; <span style="color: #3333ff;">new</span> { Username = currentItem.UserName, UserID = user.ID });</pre>
<p>All in one line. Now I personally like the sql-ish linq expressions, but for this why not fit it into one line?</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/lessons/and-then-you-hit-the-wall/" title="And then you hit the wall.">And then you hit the wall.</a></li><li><a href="http://byatool.com/general-coding/when-is-a-field-not-a-field/" title="When is a field not a field?">When is a field not a field?</a></li><li><a href="http://byatool.com/general-coding/adding-to-the-select/" title="Adding to the Select">Adding to the Select</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/linq-query-versus-just-a-select/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Match Collections Using Linq Union</title>
		<link>http://byatool.com/general-coding/union-to-find-if-two-lists-match/</link>
		<comments>http://byatool.com/general-coding/union-to-find-if-two-lists-match/#comments</comments>
		<pubDate>Fri, 22 Aug 2008 12:46:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Union]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/22/union-to-find-if-two-lists-match/</guid>
		<description><![CDATA[So let's say you have two lists you want to compare to see if they hold the same items, but the items are not equal reference. Now, if you are comparing two lists that have unique values to compare, Union is perfect. List 1 { 1, 2, 3, 4, 5 } List 2 { 2, [...]]]></description>
			<content:encoded><![CDATA[<p>So let's say you have two lists you want to compare to see if they hold the same items, but the items are not equal reference. Now, if you are comparing two lists that have unique values to compare, Union is perfect.</p>
<p>List 1 { 1, 2, 3, 4, 5 }</p>
<p>List 2 { 2, 1, 4, 3, 5 }</p>
<p>As you can see, there are no repeated values in these two lists. Easy way to figure out if all the values are the same in the two lists:</p>
<pre>  <span style="color: #3333ff;">var</span> query = (<span style="color: #3333ff;">from</span> first <span style="color: #3333ff;">in</span> firstList
            <span style="color: #3333ff;">select</span> first).Union(<span style="color: #3333ff;">from</span> second <span style="color: #3333ff;">in</span> secondlist
                                <span style="color: #3333ff;">select</span> second);

  <span style="color: #00cccc;">Assert</span>.IsTrue(query.Count() == first.Count());</pre>
<p>Why does this work? Union combine the two lists, removing any duplicates. So if everything goes correctly, the count of the new list has to match the count of either of the olds lists. After all 5 pairs of duplicate items gets reduced to a list of 5. Now, if there is anything different between the lists the count will get screwed. Why? Because even one difference will cause an extra item to show up in the list.</p>
<p>List 1 { 1, 2, 3, 4, 5 }</p>
<p>List 2 { 1, 2, 3, 4, 6 }</p>
<p>Union { 1, 2, 3, 4 , 5, 6 }</p>
<p>And it will only get worse for every mismatch.</p>
<p>Real worldish example:</p>
<pre>    <span style="color: #3333ff;">var</span> query = (<span style="color: #3333ff;">from</span> user <span style="color: #3333ff;">in</span> userListFirst
              <span style="color: #3333ff;">select</span> user.UserID).Union(<span style="color: #3333ff;">from</span> secondUser <span style="color: #3333ff;">in</span> userListSecond
                                       <span style="color: #3333ff;">select</span> second.UserID);

   <span style="color: #00cccc;"> Assert</span>.IsTrue(query.Count() == userListFirst.Count());</pre>
<p>Bonus points if you can figure out why this would fail at times. Actually, I already told you...</p>
<p>UsInGS</p>
<pre>  <span style="color: #3333ff;">using</span> System;
  <span style="color: #3333ff;">using</span> System.Linq;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/union-to-find-if-two-lists-match/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Life is fun when you are slow</title>
		<link>http://byatool.com/general-coding/life-is-fun-when-you-are-slow/</link>
		<comments>http://byatool.com/general-coding/life-is-fun-when-you-are-slow/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 20:29:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Action]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/19/life-is-fun-when-you-are-slow/</guid>
		<description><![CDATA[public void IfTrueRunMethod(Func&#60;Boolean&#62; trueMethod, Action action) { if(trueMethod()) { action(); } } Just something I made for the hell of it to remove: if(someClass != null &#38;&#38; someClass.Property == "hi") { SomeMethod(); } This can be reduced to one line... yay! IfTrueRunMethod(() =&#62; { someClass != null &#38;&#38; someClass.Property == "hi" }, () =&#62; SomeMethod()); [...]]]></description>
			<content:encoded><![CDATA[<pre><span style="color: #3333ff;">public</span> <span style="color: #3333ff;">void</span> IfTrueRunMethod(<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">Boolean</span>&gt; trueMethod, <span style="color: #00cccc;">Action</span> action)
{
  <span style="color: #3333ff;">if</span>(trueMethod())
  {
    action();
  }
}</pre>
<p>Just something I made for the hell of it to remove:</p>
<pre><span style="color: #3333ff;">if</span>(someClass != <span style="color: #3333ff;">null</span> &amp;&amp; someClass.Property == <span style="color: #cc0000;">"hi"</span>)
{
  SomeMethod();
}</pre>
<p>This can be reduced to one line... yay!</p>
<pre>IfTrueRunMethod(() =&gt; { someClass != <span style="color: #3333ff;">null</span> &amp;&amp; someClass.Property == <span style="color: #cc0000;">"hi"</span> }, () =&gt; SomeMethod());</pre>
<p>You could even transform the first part into a method if you want:</p>
<pre>IfTrueRunMethod(() =&gt; TrueMethod(someClass), () =&gt; SomeMethod());</pre>
<p>Weeeee!</p>
<pre><span style="color: #3333ff;">using</span> System;
<span style="color: #3333ff;">using</span> System.Linq;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/fizzbuzz-with-linq-extension-methods/" title="Solve FizzBuzz Using Linq Extension Methods">Solve FizzBuzz Using Linq Extension Methods</a></li><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/life-is-fun-when-you-are-slow/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Convert Enum to Dictionary: Another Silly Method</title>
		<link>http://byatool.com/utilities/another-silly-method-just-for-you/</link>
		<comments>http://byatool.com/utilities/another-silly-method-just-for-you/#comments</comments>
		<pubDate>Thu, 14 Aug 2008 18:22:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Enumeration]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/08/14/another-silly-method-just-for-you/</guid>
		<description><![CDATA[So what if you want the names and values from an Enum, but wanted them in dictionary form. Well shoot, a little bit of linq and little bit of that and you got this: public static IDictionary&#60;String, Int32&#62; ConvertEnumToDictionary&#60;K&#62;() { if (typeof(K).BaseType != typeof(Enum)) { throw new InvalidCastException(); } return Enum.GetValues(typeof(K)).Cast&#60;Int32&#62;().ToDictionary(currentItem =&#62; Enum.GetName(typeof(K), currentItem)); } [...]]]></description>
			<content:encoded><![CDATA[<p>So what if you want the names and values from an Enum, but wanted them in dictionary form. Well shoot, a little bit of linq and little bit of that and you got this:</p>
<pre><span style="color: #3333ff;">public</span> <span style="color: #3333ff;">static</span> <span style="color: #00cccc;">IDictionary</span>&lt;<span style="color: #00cccc;">String</span>, <span style="color: #00cccc;">Int32</span>&gt; ConvertEnumToDictionary&lt;K&gt;()
{
 <span style="color: #3333ff;">if</span> (<span style="color: #3333ff;">typeof</span>(K).BaseType != <span style="color: #3333ff;">typeof</span>(<span style="color: #00cccc;">Enum</span>))
 {
   <span style="color: #3333ff;">throw</span> <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">InvalidCastException</span>();
 }

 <span style="color: #3333ff;">return</span> <span style="color: #00cccc;">Enum</span>.GetValues(<span style="color: #3333ff;">typeof</span>(K)).Cast&lt;<span style="color: #00cccc;">Int32</span>&gt;().ToDictionary(currentItem =&gt; <span style="color: #00cccc;">Enum</span>.GetName(<span style="color: #3333ff;">typeof</span>(K), currentItem));
}</pre>
<p>As you might see, pretty simple.</p>
<p>Ok so ToDictionary is kind of odd looking maybe, but really isn't that big of a deal. Basically it assumes the items in the list are the value, but you need to tell it what the key is. In this case, the int values for the enum are the value for the dictionary where the name that matches said int value will become the key for the dictionary.</p>
<p>So basically, get the values for the enum. Turn that into an IEnumerable list of Int32, create a Dictionary from that.</p>
<p>USINGS!!111</p>
<pre> <span style="color: #3333ff;">using</span> System;
 <span style="color: #3333ff;">using</span> System.Collections.Generic;
 <span style="color: #3333ff;">using</span> System.Linq;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/another-silly-method-just-for-you/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
