﻿<?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; Lambda</title>
	<atom:link href="http://byatool.com/tag/lambda/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>There are 10 types of people in the world: Those who understand binary and me.</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>Linq Join Extension Method and How to Use It&#8230;</title>
		<link>http://byatool.com/c/linq-join-method-and-how-to-use-it/</link>
		<comments>http://byatool.com/c/linq-join-method-and-how-to-use-it/#comments</comments>
		<pubDate>Wed, 29 Apr 2009 17:23:31 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Join]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=607</guid>
		<description><![CDATA[I don't like using the query syntax when it comes to Linq to AnythingButTheKitchenSink . Not sure why. Mostly, I guess, is that I seem to have a liking for Funcs and Actions to the point of stupidity and although you can work them into the query syntax, it just doesn't look right. Now with [...]]]></description>
			<content:encoded><![CDATA[<p>I don't like using the query syntax when it comes to Linq to AnythingButTheKitchenSink . Not sure why. Mostly, I guess, is that I seem to have a liking for Funcs and Actions to the point of stupidity and although you can work them into the query syntax, it just doesn't look right.</p>
<p>Now with most of the Linq methods like Where or First, it's simple once you understand lamdba expressions:</p>
<pre>.SomeMethod(someField =&gt; someField.Property == value);</pre>
<p>Now what about join?</p>
<pre><img src="http://byatool.com/wp-content/uploads/2009/04/join.png" alt="JOINHELL" /></pre>
<p>So inner selector with an outer selector and a selector selects a selecting selector. Right got it.</p>
<p>Well let's try to break it down. First part is</p>
<pre><span style="color: #0000ff;">this</span> <span style="color: #008080;">IEnumerable</span>&lt;<span style="color: #008080;">TOuter</span>&gt;</pre>
<p>So being that this is an extension method meaning this is the collection you are using this method on.</p>
<pre><span style="color: #008080;">IEnumerable</span>&lt;<span style="color: #008080;">TInner</span>&gt; inner</pre>
<p>So second field must be the list you want to join to. Ok so far.</p>
<pre><span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">TOuter</span>, <span style="color: #008080;">TKey</span>&gt; outerKeySelector</pre>
<p>Now this is where it gets a little odd looking. We know we have Outer and Inner lists so there needs to be a way to join on something. Say Outer is User and Inner is UserAddress. Most likely you will have a UserID on both lists. If not, you do now. So basically what this part of the method is saying is "Give me the stupid key on the Outer (User) list that I should care about."</p>
<pre>, user =&gt; user.UserID,</pre>
<p>Next part:</p>
<pre><span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">TInner</span>, <span style="color: #008080;">TKey</span>&gt; innerKeySelector</pre>
<p>Pretty much the same thing, except now it needs the key from the Innerlist (UserAddress):</p>
<pre>, address =&gt; address.UserID,</pre>
<p>Now for the fun part:</p>
<pre><span style="color: #008080;">Func</span>&lt;<span style="color: #008080;">TOuter</span>, <span style="color: #008080;">TInner</span>, <span style="color: #008080;">TResult</span>&gt; resultSelector</pre>
<p>Sa...say what? Ok this may look weird at first but you'll hate yourself for not seeing it. It's just asking you what to select from the two lists as some kind of hybrid object. See, you have to remember that with these linq methods, each method will produce a list. You can't just chain them together and have it remember every list you've made:</p>
<pre>   user.Where(user =&gt; user.UserID &gt; 1) <span style="color: #008000;">// gives me a list of users</span>
         .Select(user =&gt; new { user.UserName, user.UserAddress, user.UserID } <span style="color: #008000;">
         //Gives me new items with user name, address, and user id</span></pre>
<p>From this simple method chain, the end list is NOT the same as the one you started with or the one produced by the where method.</p>
<p>The last part of the Join method needs you to tell it what it's going to produce from this join. Now it probably could just guess and include both lists, but that could be seen as sloppy and ultimately this gives you the choice of what exactly needs to be taken after the join. So:</p>
<pre>, (user, address) =&gt; new { user, address});</pre>
<p>So in this case, the newly created and joined list with be a list of items that have a user and address attached to it much like if you had a list of:</p>
<pre><span style="color: #0000ff;">class</span> UserAddressHybrid()
{
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">User</span> user { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">UserAddress</span> userAddress { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
}</pre>
<p>So in other words, WHAT DO YOU WANT YOUR RESULTS TO LOOK LIKE?</p>
<p>In full it would look something like:</p>
<pre>user.Join(address =&gt; address.User.UserID,  <span style="color: #008000;">//IEnumerable&lt;TInner&gt; inner</span>
             user =&gt; user.UserID,  <span style="color: #008000;">//Func&lt;TOuter, TKey&gt; outerKeySelector</span>
             address =&gt; address.UserID,  <span style="color: #008000;">//Func&lt;TInner, TKey&gt; innerKeySelector</span>
             (user, address) =&gt; new { user, address});  <span style="color: #008000;">//Func&lt;TOuter, TInner, TResult&gt; resultSelector</span></pre>
<p>Not so hard anymore, is it?  You can start kicking yourself 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/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><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/c/linq-join-method-and-how-to-use-it/feed/</wfw:commentRss>
		<slash:comments>3</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>Cannot Resolve Method, Can&#8217;t Infer Return Type, and Funcs</title>
		<link>http://byatool.com/net-issues/funcs-type-inference-and-linq-and-bears-oh-my/</link>
		<comments>http://byatool.com/net-issues/funcs-type-inference-and-linq-and-bears-oh-my/#comments</comments>
		<pubDate>Thu, 06 Nov 2008 20:07:11 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[.Net Issues]]></category>
		<category><![CDATA[Anonymous Methods]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=79</guid>
		<description><![CDATA[So ran into this today and the answer was actually a lot easier to understand than I thought it would be. Say you want to order a list of objects by a number. Seems simple. Now if you have been paying attention you would know I like using Funcs. Func&#60;SomeClass, Int32&#62; orderByNumber = currentClass =&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>So ran into this today and the answer was actually a lot easier to understand than I thought it would be.</p>
<p>Say you want to order a list of objects by a number. Seems simple. Now if you have been paying attention you would know I like using Funcs.</p>
<pre>  <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">SomeClass</span>, <span style="color: #33cccc;">Int32</span>&gt; orderByNumber =
    currentClass =&gt;  currentClass.SomeNumber;

  anotherCollection = someCollection.OrderBy(orderByNumber);</pre>
<p>Seems simple, but what if you wanted to use a method already defined in the class?</p>
<pre>  <span style="color: #0000ff;">private</span> <span style="color: #33cccc;">Int32</span> ReturnNumber(<span style="color: #33cccc;">SomeClass</span> currentClass)
  {
    <span style="color: #0000ff;">return</span> currentClass.SomeNumber;
  }</pre>
<p>It seems like this could be the way to go, right?</p>
<pre>  someCollection.OrderBy(ReturnNumber);</pre>
<p>Compile and BOOOOOOM you get an error. It says it can't infer the return type of the method. Wait what? It's pretty obvious right, it's an integer. It had no problem inferring from the <span style="color: #33cccc;">Func</span> and you have to figure that the method itself is "typed" also. Well here's the problem (And you're dumb for not knowing this, but I'm not because I'm immune to dumb), ReturnNumber isn't a method, it's part of a method group. You can have a million (well maybe not that many) methods named ReturnNumber, all with different parameters. Why is this a problem? Well let's use lambda expressions:</p>
<pre>  someCollection.OrderBy(currentClass =&gt;  currentClass.SomeNumber);</pre>
<p>At this point it knows two things: currentClass is a <span style="color: #33cccc;">SomeClass</span> and there is a Method that takes in a <span style="color: #33cccc;">SomeClass</span> and returns something. So with that in mind, it looks for such a method and finds the return type. This is no different with the <span style="color: #33cccc;">Func</span> since the <span style="color: #33cccc;">Func</span> is basically unique due to it being a named field. After all you can't have two fields named orderByNumber, but you can have many methods named ReturnNumber. That is where the problem is. When you use the second example:</p>
<pre>  someCollection.OrderBy(ReturnNumber);</pre>
<p>It can infer the <span style="color: #33cccc;">SomeClass</span> from the list and it sees the method. For there it has to find the method's return type. Wait, which method? If i Have 10 overloads, each with different return types, how does it know what type to use?  Well the answers is, it doesn't.  So basically you're screwed.  Sucks, huh?</p>
<p>Side note: This works</p>
<pre>  <span style="color: #33cccc;">Func</span>&lt;<span style="color: #33cccc;">SomeClass</span>, <span style="color: #33cccc;">Int32</span>&gt; orderByNumber = ReturnNumber;</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/net-issues/funcs-type-inference-and-linq-and-bears-oh-my/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Another removing Lambda &#8220;trick&#8221;</title>
		<link>http://byatool.com/general-coding/another-removing-lambda-trick/</link>
		<comments>http://byatool.com/general-coding/another-removing-lambda-trick/#comments</comments>
		<pubDate>Mon, 03 Nov 2008 17:57:57 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Action]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=73</guid>
		<description><![CDATA[And by trick, I mean I was too slow to realize that: someDictionary.Add("Hi", (Boolean doThis) =&#62; SomeMethod(doThis)); Can be done this way: someDictionary.Add("Hi", SomeMethod); Where the dictionary is: Dictionary&#60;String, Action&#60;Bool&#62;&#62; someDictionary; someDictionary = new Dictionary&#60;String, Action&#60;Bool&#62;&#62;(); And SomeMethod is: void SomeMethod(Boolean doSomething) { //Something is to be done! } Which as far as I know, [...]]]></description>
			<content:encoded><![CDATA[<p>And by trick, I mean I was too slow to realize that:</p>
<pre>  someDictionary.Add(<span style="color: #ff0000;">"Hi"</span>, (<span style="color: #33cccc;">Boolean</span> doThis) =&gt; SomeMethod(doThis));</pre>
<p>Can be done this way:</p>
<pre>  someDictionary.Add(<span style="color: #ff0000;">"Hi"</span>, SomeMethod);</pre>
<p>Where the dictionary is:</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;">Bool</span>&gt;&gt; someDictionary;
  someDictionary = <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>&lt;<span style="color: #33cccc;">Bool</span>&gt;&gt;();</pre>
<p>And SomeMethod is:</p>
<pre><span style="color: #0000ff;">void</span> SomeMethod(<span style="color: #33cccc;">Boolean</span> doSomething)
{
  <span style="color: #339966;">//Something is to be done!
</span>}</pre>
<p>Which as far as I know, removes a step from the whole process. What does that mean? Well if you break the first one down into an anonymous method, it would look like this:</p>
<pre>  someDictionary.Add(<span style="color: #ff0000;">"Hi"</span>, <span style="color: #0000ff;">delegate</span>(<span style="color: #33cccc;">Boolean</span> doThis){ SomeMethod(doThis); });</pre>
<p>I am assuming this would create a reference to a completely new method as opposed to the second example which just uses the already existing method's reference. Fun yah?</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/and-some-days-i-love-programming/" title="And some days I love programming">And some days I love programming</a></li><li><a href="http://byatool.com/general-coding/i-likz-demz-linq/" title="I likz demz linq">I likz demz linq</a></li><li><a href="http://byatool.com/general-coding/ienumerable-extention-methods-and-action/" title="IEnumerable Extention Methods and Action">IEnumerable Extention Methods and Action</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/another-removing-lambda-trick/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>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>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>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>And some days I love programming</title>
		<link>http://byatool.com/general-coding/and-some-days-i-love-programming/</link>
		<comments>http://byatool.com/general-coding/and-some-days-i-love-programming/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 22:53:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/17/and-some-days-i-love-programming/</guid>
		<description><![CDATA[This is the newest edition of Linq madness. So I added an OrderBy to my lame dynamic query thing. private static IQueryable&#60;User&#62; GetUserList(Expression&#60;Func&#60;User, Boolean&#62;&#62; whereClause, Expression&#60;Func&#60;User, String&#62;&#62; orderBy) { var query = (from user in GetDataContext().Users select user).Where(whereClause).OrderBy(orderBy); return query; } Now you will notice there is a new Expression in town and it's name [...]]]></description>
			<content:encoded><![CDATA[<p>This is the newest edition of Linq madness. So I added an OrderBy to my lame dynamic query thing.</p>
<pre><span style="color: #3333ff;">private static</span> <span style="color: #00cccc;">IQueryable</span>&lt;<span style="color: #00cccc;">User</span>&gt; GetUserList(<span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Boolean</span>&gt;&gt; whereClause, <span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">String</span>&gt;&gt; orderBy)
{
<span style="color: #3366ff;">    <span style="color: #3333ff;">var </span></span>query = (<span style="color: #3333ff;">from </span>user <span style="color: #3333ff;">in </span>GetDataContext().Users
      <span style="color: #3333ff;">       select </span>user).Where(whereClause).OrderBy(orderBy);

<span style="color: #3333ff;">    return </span>query;
}</pre>
<p>Now you will notice there is a new Expression in town and it's name isn't Reggie Hammond. It is my order by Expression which uses a <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">String</span>&gt;. It took me a minute to figure out how this works. I thought it was somehow in need of the property name to order by, but in reality it is looking for a list of strings to order by. Simple. I could do something like: (Ignore the WhereLikeFirstNameLastNameUserName for now)</p>
<pre><span style="color: #3333ff;">    return </span>GetUserList
           (
            WhereLikeFirstNameLastNameUserName(name),
            currentUser =&gt; currentUser.UserName
           ).ToList();</pre>
<p>But that's boring. I want to be able to pass a method that would give the correct string to orderby somewhat cleaner. In comes a method that returns an Expression. OooOoOOo.</p>
<pre><span style="color: #3333ff;">private static</span> <span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">String</span>&gt;&gt; SortOnUserName()
{
<span style="color: #3333ff;">    return </span>currentUser =&gt; currentUser.UserName;
}</pre>
<p>So now it looks like:</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">IList</span>&lt;User&gt;<span style="color: #00cccc;"> </span>GetUserListByLikeName(<span style="color: #00cccc;">String </span>name)
{
<span style="color: #3333ff;">   return </span>GetUserList
          (
           WhereLikeFirstNameLastNameUserName(name),
           SortOnUserName()
          ).ToList();
}</pre>
<p>Cleaner... Now what is WhereLikeFirstNameLastNameUserName? Simple, that is my where Expression just being returned in this method:</p>
<pre><span style="color: #3333ff;">private static</span> <span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Boolean</span>&gt;&gt; WhereLikeFirstNameLastNameUserName(<span style="color: #00cccc;">String </span>name)
{
<span style="color: #3333ff;">   return </span>currentUser =&gt; <span style="color: #00cccc;">SqlMethods</span>.Like(currentUser.UserName, <span style="color: #cc0000;">"%"</span> + name + <span style="color: #cc0000;">"%"</span>)
   || <span style="color: #00cccc;">SqlMethods</span>.Like(currentUser.FirstName, <span style="color: #cc0000;">"%"</span> + name + <span style="color: #cc0000;">"%"</span>)
   || <span style="color: #00cccc;">SqlMethods</span>.Like(currentUser.LastName, <span style="color: #cc0000;">"%"</span> + name + <span style="color: #cc0000;">"%"</span>);
}</pre>
<p>By the way, <span style="color: #00cccc;">SqlMethods</span>.Like is just a built in method used only with Linq to Sql. Probably shouldn't have used it in this example but oh well. Live with it.</p>
<p>OH NO NOT THE USINGS!!</p>
<pre><span style="color: #3366ff;">using</span> System;
<span style="color: #3333ff;">using </span>System.Collections.Generic;
<span style="color: #3333ff;">using </span>System.Data.Linq.SqlClient;
<span style="color: #3333ff;">using </span>System.Linq;
<span style="color: #3333ff;">using </span>System.Linq.Expressions;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/i-likz-demz-linq/" title="I likz demz linq">I likz demz linq</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/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><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></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/and-some-days-i-love-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I likz demz linq</title>
		<link>http://byatool.com/general-coding/i-likz-demz-linq/</link>
		<comments>http://byatool.com/general-coding/i-likz-demz-linq/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 16:30:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/17/i-likz-demz-linq/</guid>
		<description><![CDATA[So today I had this weird need to try creating a sort of dynamic linq thing in which I could query a User list but not have to write a Linq query for every method. I just wanted to make a method that would return the correct query that I wanted based on a simple [...]]]></description>
			<content:encoded><![CDATA[<p>So today I had this weird need to try creating a sort of dynamic linq thing in which I could query a User list but not have to write a Linq query for every method. I just wanted to make a method that would return the correct query that I wanted based on a simple "dynamic" where clause. Well part of the reason this should be easy is if you look at the Where extension method on an IEnumerable collection, you will see it needs a <span style="color: #00cccc;">Func</span>&lt;T, K&gt; where T is the type of the items in the list. So ding!, create a method that takes in a <span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Boolean</span>&gt; and puts it in them thar where clause. Then you could easily use a lambda expression to create the Func. At first you might thing something like this:</p>
<pre><span style="color: #3333ff;">private static</span> <span style="color: #00cccc;">IQueryable</span>&lt;<span style="color: #00cccc;">User</span>&gt; GetUserList(<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Boolean</span>&gt; whereClause)
{
<span style="color: #3333ff;">  var </span>query = <span style="color: #3333ff;">from </span>user <span style="color: #3366ff;">in </span>Users
          <span style="color: #3333ff;">  where </span>whereClause(user)
            <span style="color: #3333ff;">select </span>user;

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

<span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">IList</span>&lt;<span style="color: #00cccc;">User</span>&gt; GetUserListByUserName(<span style="color: #00cccc;">String </span>userName)
{
<span style="color: #3333ff;">  return </span>GetUserList(currentUser =&gt; currentUser.UserName == userName).ToList();
}</pre>
<p>AND YOU WOULD BE WRONG! I only know this because... eh... I saw a friend of mine try this and it failed. Fact is, the Linq where doesn't take in a Func, but rather it expects and Expression. So no big deal right? Slap on an expression and go... except you can't keep the same syntax. (Trust me, my... friend tried) Being the absolute genius that I am, I offered my friend a solution, and it's slightly ugly:</p>
<pre><span style="color: #3333ff;">private static</span> <span style="color: #00cccc;">IQueryable</span>&lt;<span style="color: #00cccc;">User</span>&gt; GetUserList(<span style="color: #00cccc;">Expression</span>&lt;<span style="color: #00cccc;">Func</span>&lt;<span style="color: #00cccc;">User</span>, <span style="color: #00cccc;">Boolean</span>&gt;&gt; whereClause)
{
<span style="color: #3333ff;">  var </span>query = (<span style="color: #3333ff;">from </span>user <span style="color: #3333ff;">in </span>Users
          <span style="color: #3333ff;">  select </span>user).Where(whereClause);

<span style="color: #3333ff;">  return </span>query;
}</pre>
<p>Could be used like:</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">IList</span>&lt;<span style="color: #00cccc;">User</span>&gt; GetUserList()
{
<span style="color: #3333ff;">  return </span>GetUserList(currentUser =&gt; <span style="color: #3333ff;">true</span>).ToList();
}</pre>
<p>Or</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">IList</span>&lt;<span style="color: #00cccc;">User</span>&gt; GetUserListByFirstName(<span style="color: #00cccc;">String </span>firstName)
{
<span style="color: #3333ff;">  return </span>GetUserList(currentUser =&gt; currentUser.FirstName == firstName).ToList();
}</pre>
<p>Yeah, not the prettiest of things, but it is what it is. I'm not even sure this is useful yet. Still screwing around with it. Does cut down on code for easy queries.</p>
<p>AND NOW FOR THE ASSEMBLIES!</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.Linq.Expressions;</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><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><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/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><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></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/i-likz-demz-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the ForEach method on List Collections</title>
		<link>http://byatool.com/general-coding/using-the-foreach-method-on-list-collections/</link>
		<comments>http://byatool.com/general-coding/using-the-foreach-method-on-list-collections/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 13:18:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[ForEach]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/06/26/using-the-foreach-method-on-list-collections/</guid>
		<description><![CDATA[public static StateCollection GetByName(String partialName) { StateCollection returnValue; returnValue = new StateCollection(); //baseList is some list I wasn't nice enough to show where it came from. //It's just a list of states. Get over it. var stateList = from state in baseList where state.Name.StartsWith(partialName) select new State(state.Name, state.Code); stateList.ToList().ForEach(currentState =&#62; returnValue.Add(currentState)); return returnValue; } So [...]]]></description>
			<content:encoded><![CDATA[<pre><strong>
public static StateCollection GetByName(String partialName)
{
 StateCollection returnValue;

 returnValue = new StateCollection();

<span style="color: #009900;">  //baseList is some list I wasn't nice enough to show where it came from.</span>
<span style="color: #009900;">  //It's just a list of states.  Get over it.</span>
 var stateList = from state in baseList
                 where state.Name.StartsWith(partialName)
                 select new State(state.Name, state.Code);

 stateList.ToList().ForEach(currentState =&gt; returnValue.Add(currentState));

 return returnValue;
}
</strong></pre>
<p>So what is done here:</p>
<p>Basically I am using a linq expression to get states from a list of states (Like Michigan, Illinois, or Canada) based on name. No big deal. Then I take the query and produce a List from it. AMAZIN!</p>
<pre><strong>
stateList.ToList().<span style="color: #339999;">ForEach(curretState =&gt; returnValue.Add(curretState));</span>
</strong></pre>
<p>ForEach is an extension method for List&lt;&gt;. Now if you remember from previous posts, that means it resides in a static class somewhere that "tacks" it on to the List&lt;&gt; class. Basically this method acts like a typical foreach loop. (You know, go through the list and do something. Or nothing. I suppose you could just loop through if you wanted to. I won't tell you how to live your life.) Simple but in my opinion, much cleaner looking.</p>
<p>I mean I could do this:</p>
<pre><strong>
public static StateCollection GetByName(String partialName)
{
 StateCollection returnValue;

 returnValue = new StateCollection();

 foreach(State currentState in baseList)
 {
   if(currentState.Name.StartsWith(partialName)
   {
     returnValue.Add(currentState);
   }
 }

 return returnValue;
}
</strong></pre>
<p>Really it's just up to what you prefer. (And I'm sure you could drive a car with no power brakes. You'll still get there.) Also, I really didn't need the linq expression since I could have done this all with ForEach (Provided baseList is IEnumerable).</p>
<p>One last note, all IEnumerable collections have the ToList() method (And a bunch of other ones for that matter.)</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/c/linq-join-method-and-how-to-use-it/" title="Linq Join Extension Method and How to Use It&#8230;">Linq Join Extension Method and How to Use It&#8230;</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/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><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/using-the-foreach-method-on-list-collections/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>IEnumerable Extention Methods and Action</title>
		<link>http://byatool.com/general-coding/ienumerable-extention-methods-and-action/</link>
		<comments>http://byatool.com/general-coding/ienumerable-extention-methods-and-action/#comments</comments>
		<pubDate>Wed, 25 Jun 2008 20:42:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Action]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[IEnumerable]]></category>
		<category><![CDATA[Lambda]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/06/25/ienumerable-extention-methods-and-action/</guid>
		<description><![CDATA[This may be slightly off, but I've pretty much figured them out and how they work with lambda expressions. First off, Lambda expressions. These are the odd looking currentItem =&#62; expressions you might see in my examples. They are a little misleading, at least to me they were. When I saw: ilist.SomeExtension(currentItem =&#62; SomeMethod(currentItem)); I [...]]]></description>
			<content:encoded><![CDATA[<p>This may be slightly off, but I've pretty much figured them out and how they work with lambda expressions.</p>
<p>First off, Lambda expressions. These are the odd looking currentItem =&gt; expressions you might see in my examples. They are a little misleading, at least to me they were. When I saw:</p>
<pre><strong>
 ilist.SomeExtension(currentItem =&gt; SomeMethod(currentItem));
</strong></pre>
<p>I thought that meant:</p>
<p>Loop through the list of currentItems and use that method. Well that's sort of it, but really misleading. In order to fully understand some of the more fun extension methods and lamba fun, a clearer explanation is needed. (I say fun instead of more complicated since I think the word "complicated" is exaggerating .)</p>
<p>What</p>
<pre><strong>
 ilist.SomeExtension(currentItem =&gt; SomeMethod(currentItem));
</strong></pre>
<p>really means is that I am going to call this method SomeExtension, give it a method to use, and that's it. What it does with that method is the heart of what SomeExtension is.</p>
<p><em>Small note: currentItem =&gt; helps to infer the type of whatever it is that you're going to pass into SomeMethod.</em></p>
<p>Say SomeExtension looks like this:</p>
<pre><strong>
public static void SomeExtension(this IList&lt;I&gt; items, &lt;I&gt;, Action&lt;I&gt; action)
{
   SomeExtension(I item in items)
  {
    action(item);
  }
}
</strong></pre>
<p>Now what is action? It's basically a place holder for a method that returns nothing. Only thing it cares about is what it has to send in, and that is Type I. From there, it will call the method it points to and magic happens.<br />
<em>Small note: What the hell is items? Well that is the list that you called this method from. This is an example of an extension method. Extension methods, in short, allow a person to "tack" a method onto a class without changing the class itself. <strong>this IList&lt;I&gt; items</strong> tells me that the extension method SomeExtension will be "tacked" onto ANY IList. </em></p>
<p>In this instance, what action really looks like is this:</p>
<pre><strong>
public void action
(
  delegate (I Item)
  {
    SomeMethod(item);
  }
)
</strong></pre>
<p>As you can see, the SomeMethod from the original SomeExtension call comes into play now. The above examples really could be the List&lt;&gt; extention method of ForEach most likely looks like.</p>
<p>Now what might not look familiar there is the delegate key word. This is what's called an anonymous method. Basically, this allows you to create delegates on the fly. An example of this would be List&lt;&gt;.Contains. A normal call to this might be:</p>
<pre><strong>
someList.Contains(delegate(String currentItem){ return currentItem == someVariable); });
</strong></pre>
<p>What this says is that contains will do whatever it does, but it will use the method you have provided to do that. Most likely the method itself looks like (And this is pseudo code for sure):</p>
<pre><strong>
Boolean contains;

contains = false;

foreach(String currentItem in theList)
{
  contains = delegate(currentItem);

  if(contains)
  {
     exit;
  }
}

return contains;
</strong></pre>
<p>Although, this is misleading in this post since this would deal with Func not Action.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/another-removing-lambda-trick/" title="Another removing Lambda &#8220;trick&#8221;">Another removing Lambda &#8220;trick&#8221;</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/using-the-foreach-method-on-list-collections/" title="Using the ForEach method on List Collections">Using the ForEach method on List Collections</a></li><li><a href="http://byatool.com/c/linq-join-method-and-how-to-use-it/" title="Linq Join Extension Method and How to Use It&#8230;">Linq Join Extension Method and How to Use It&#8230;</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/ienumerable-extention-methods-and-action/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
