﻿<?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; Linq</title>
	<atom:link href="http://byatool.com/tag/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://byatool.com</link>
	<description>This is my recorded stumbling through ASP.Net, Framework 3.5, C# 3.0, Ajax, Javascript, and Love.  Stay, learn, destroy.  It's your life.</description>
	<lastBuildDate>Thu, 03 May 2012 17:28:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Create An X  Delimited String From A Char List Using Linq Aggregate</title>
		<link>http://byatool.com/lessons/create-an-x-delimited-string-from-a-char-list-using-linq-aggregate/</link>
		<comments>http://byatool.com/lessons/create-an-x-delimited-string-from-a-char-list-using-linq-aggregate/#comments</comments>
		<pubDate>Thu, 08 Mar 2012 19:16:56 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Aggregate]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=2510</guid>
		<description><![CDATA[A quick example of how to use the Aggregate method to create a string of delimited members, or in this case characters. You might wonder why this example, or at least you should. It&#8217;s true, the character list to delimited string is pretty useless, but some idiot from where I work needed it. [TestMethod] public [...]]]></description>
			<content:encoded><![CDATA[<p>A quick example of how to use the Aggregate method to create a string of delimited members, or in this case characters. You might wonder why this example, or at least you should. It&#8217;s true, the character list to delimited string is pretty useless, but some <a href="http://byatool.com/andre/">idiot from where I work</a> needed it.</p>
<pre>[<span style="color: #008080;">TestMethod</span>]
<span style="color: #0000ff;">public void</span> GetStringFromCharacters()
{
    <span style="color: #0000ff;">var</span> charList = <span style="color: #008080;">Enumerable</span>.Range(0, 10).Select(x =&gt; 'a').ToList();

    charList
        .Aggregate(<span style="color: #800000;">""</span>, (inner, outer) =&gt; inner + outer.ToString() + <span style="color: #800000;">","</span>)
        .Should()
        .Be(<span style="color: #800000;">"a,a,a,a,a,a,a,a,a,a"</span>);
}
</pre>
<p><br/><br />
The big thing here is the &#8220;&#8221; in the Aggregate method signature.  That basically says that Inner is a string.  If I didn&#8217;t have that specified, both inner and outer would be a character.<br />
<br/><br />
YAY</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/create-an-x-delimited-string-from-a-char-list-using-linq-aggregate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Linq and Stack&#8230; Take versus Pop</title>
		<link>http://byatool.com/lessons/linq-and-stack-take-versus-pop/</link>
		<comments>http://byatool.com/lessons/linq-and-stack-take-versus-pop/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 18:34:14 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[IEnumerable]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Stack]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=1856</guid>
		<description><![CDATA[So this might be filed under &#8220;Who f&#8212;ing cares&#8221; but I thought it was somewhat interesting. If you&#8217;ve ever used a Stack, you should be familiar with Pop and Peek. If not, here&#8217;s a little diddy from a guy named diddy. Actually that&#8217;s a lie. I have no affiliation Sean &#8220;Puffy&#8221; &#8220;Puff Daddy&#8221; &#8220;P Diddy&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p>So this might be filed under &#8220;Who f&#8212;ing cares&#8221; but I thought it was somewhat interesting.  If you&#8217;ve ever used a Stack, you should be familiar with Pop and Peek.  If not, here&#8217;s a little diddy from a guy named diddy.  Actually that&#8217;s a lie.  I have no affiliation Sean &#8220;Puffy&#8221; &#8220;Puff Daddy&#8221; &#8220;P Diddy&#8221; &#8220;Whatever he&#8217;s called now&#8221; Combs.  We do share the same first name though.  (Annnnnd wait for incoming lawsuit over using his name on this site)</p>
<p>A stack is a first in last in first out structure that in the .Net world uses two methods to get values back from it:  Pop and Peek.  Pop will give you the item AND remove it from the stack.  Peek will merely give you the item but leave it safely on the stack.</p>
<p>What&#8217;s the point of this post?  I&#8217;ll tell you when I find out.</p>
<p>Now when using Linq with a stack, you might get in trouble if you assume the Take method uses pop to get the value:</p>
<pre>  <span style="color: #0000ff;">return</span> stackToUse.Take(count).ToList();</pre>
<p>You would think that this would use Pop since Pop really is the &#8220;natural&#8221; (For lack of a better word) function of a stack.  Most languages can guarantee a Push and Pop for stacks, but not all languages have a Peek.  So it would be normal to assume the default is Pop.  Problem is:  It&#8217;s not.  The Take method actually uses the Peek method.  So these two methods will give a completely different return:</p>
<pre>    <span style="color: #008000;">///Uses Pop</span>
    <span style="color: #008000;">///  Return list with have "count" number of items and stackToUse will have the original</span>
    <span style="color: #008000;">///    count of items minus "count"</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">stati</span>c <span style="color: #008080;">List</span>&lt;<span style="color: #008080;">Object</span>&gt; CreateListFromPopOnStack(<span style="color: #008080;">Stack</span>&lt;<span style="color: #008080;">Object</span>&gt; stackToUse, <span style="color: #008080;">Int32</span> count)
    {
      <span style="color: #0000ff;">return</span> Enumerable.Range(0, count).Select(item =&gt; stackToUse.Pop()).ToList();
    }

    <span style="color: #008000;">///Uses Take/Peek</span>
    <span style="color: #008000;">///  Return list will have "count" number of items and stackToUse will have still have</span>
    <span style="color: #008000;">///     the same number of items it came in with.</span>
    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">List</span>&lt;<span style="color: #008080;">Object</span>&gt; CreateListFromTakeOnStack(<span style="color: #008080;">Stack</span>&lt;<span style="color: #008080;">Object</span>&gt; stackToUse, <span style="color: #008080;">Int32</span> count)
    {
      <span style="color: #0000ff;">return</span> stackToUse.Take(count).ToList();
    }</pre>
<p>In the end, this is a rare case you will actually need to know, but what the hell?  Why not know it?</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/linq-and-stack-take-versus-pop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match</title>
		<link>http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/</link>
		<comments>http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 17:26:32 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Lessons]]></category>
		<category><![CDATA[Hash]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Test]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=777</guid>
		<description><![CDATA[Ok so with MVC comes the use of Routes which calls in the need to compare request values to see which route to use. Now before I even bother with that headache (Although it&#8217;s getting better AND will be a post) I ran into a situation where I would have to check a passed in [...]]]></description>
			<content:encoded><![CDATA[<p>Ok so with MVC comes the use of Routes which calls in the need to compare request values to see which route to use. Now before I even bother with that headache (Although it&#8217;s getting better AND will be a post) I ran into a situation where I would have to check a passed in string against a list of strings to see if it matches any of them.</p>
<p>One thing I like to do is use Dictionaries. They are just plain convenient when it comes to looking things up or <a href="http://byatool.com/index.php/general-coding/the-switch-remover/">matching values to get methods</a>. But what if I don&#8217;t really have a value to find with a key? What if finding the key is all that matters? Say I have a list of strings and I just want to know if the list contains that string, sounds like a job for an array or list right? Wouldn&#8217;t it be silly to create a dictionary like:</p>
<pre>  <span style="color: #008080;">Dictiontary</span>&lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">String</span>&gt; someList = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Dictiontary</span>&lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">String</span>&gt;();
  someList.Add(<span style="color: #800000;">"INeedThis"</span>, <span style="color: #800000;">""</span>); someList.Add(<span style="color: #800000;">"ThisToo"</span>, <span style="color: #800000;">""</span>);</pre>
<p>and do this:</p>
<pre>  if(someList.ContainsKey(<span style="color: #800000;">"INeedThis"</span>))</pre>
<p>If I don&#8217;t actually care about the attached value? I&#8217;m sure I&#8217;m breaking a rule somewhere&#8230; but what if it was faster overall? What if ContainsKey is faster than a list using Any, Contains, FirstOrDefault, or where? Turns out it is. Here&#8217;s the method I used.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> TimeRun(<span style="color: #008080;">Holder</span> toHold)
  {
    <span style="color: #008080;">Int32</span> maxLength = 1000;

    <span style="color: #008080;">Dictionary</span>&lt;<span style="color: #008080;">String</span>, <span style="color: #008080;">String</span>&gt; stringDictionary = Enumerable.Range(0, maxLength).Select(item =&gt; RandomTool.RandomString(item)).ToDictionary(item =&gt; item, item =&gt; item);
    <span style="color: #008080;">List</span>&lt;<span style="color: #008080;">String</span>&gt; stringList = stringDictionary.Select(item =&gt; item.Key).ToList();

    <span style="color: #008080;">String</span> chosenString = stringList[RandomTool.RandomInt32(0, maxLength)];

    <span style="color: #008080;">Stopwatch</span> runTime = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Stopwatch</span>();

    runTime.Start();
    stringDictionary.ContainsKey(chosenString);
    runTime.Stop();
    toHold.DictionaryContainsKeyTime = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">String</span> junk = stringDictionary[chosenString];
    runTime.Stop();
    toHold.DictionaryStraightIndexCheck = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">Boolean</span> junkThree = stringList.Contains(chosenString);
    runTime.Stop();
    toHold.ListContains = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">Boolean</span> junkTwo = stringList.Any(item =&gt; item == chosenString);
    runTime.Stop();
    toHold.ListLinqAny = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">String</span> junkFour = stringList.First(item =&gt; item == chosenString);
    runTime.Stop();
    toHold.ListLinqFirst = runTime.ElapsedTicks;
    runTime.Reset();

    runTime.Start();
    <span style="color: #008080;">IEnumerable</span>&lt;<span style="color: #008080;">String</span>&gt; junkFive = stringList.Where(item =&gt; item == chosenString);
    <span style="color: #0000ff;">if</span> (junkFive.FirstOrDefault() != String.Empty)
    {

    }
    runTime.Stop();
    toHold.ListLinqWhere = runTime.ElapsedTicks;
    runTime.Reset();
  }</pre>
<p>Crazy simple, and why shouldn&#8217;t it? Am I right? Am I right? Ok. As you can see, I gave all the methods a run and timed them using StopWatch. And then I ran it a given amount of times, 200 in this code but I tried up to 10000 also. (I&#8217;ll put the test code at the end) The test was to go through a list of a thousand strings, each string increasing in length. (Yeah I could have done random size strings but I&#8217;m lazy)</p>
<p>What did I find out? Well if it didn&#8217;t throw an exception, a straight index search on a dictionary is fastest:</p>
<pre>someList[<span style="color: #800000;">"INeedThis"</span>]</pre>
<p>And pretty consistently fast. Around 2600 ticks or so on average on multiple runs. (so 10 iterations of parent method running 200-10000 interations of the test method) Next fastest was the ContainsKey method on the dictionary, usually around 2-4 times faster than the next in line good old List.Contains. What I did find surprising is that all the Linq methods failed on this one. I figured that once the first run was through, it would be at least as fast as Contains. (Linq always sucks the first time through) Yeah not so much though. Contains was always faster. Sometimes it was close. Sometimes not even. Here are some example runs:</p>
<pre>Dictionary_ContainsKey: 15805
Dictionary_StraightIndexCheck: 2926
List_Contains: 34559
List_LinqAny: 96575
List_LinqFirst: 56541
List_LinqWhere: 64678 

Dictionary_ContainsKey: 7264
Dictionary_StraightIndexCheck: 2676
List_Contains: 29970
List_LinqAny: 41280
List_LinqFirst: 58313
List_LinqWhere: 45669 

Dictionary_ContainsKey: 6773
Dictionary_StraightIndexCheck: 2636
List_Contains: 32366
List_LinqAny: 38670
List_LinqFirst: 33859
List_LinqWhere: 41288</pre>
<p>All in ticks. Now mind you, none of these are horribly slow so it probably just comes down to reability and ease of understanding. Personally I like the Dictionary way, so at least speed wise I&#8217;m on track. As for looks? That&#8217;s a personal thing.</p>
<p>Rest of the code. Here is the parent method. This is a unit test hense the .Assert but it could easily be adapted to any output.</p>
<pre>  [<span style="color: #008080;">TestMethod</span>]
  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> RunTime()
  {
    <span style="color: #008080;">Int64</span> overallDictionaryContainsKeyTime = 0;
    <span style="color: #008080;">Int64</span> overallDictionaryStraightIndexCheck = 0;
    <span style="color: #008080;">Int64</span> overallListContains = 0;
    <span style="color: #008080;">Int64</span> overallListLinqAny = 0;
    <span style="color: #008080;">Int64</span> overallListLinqFirst = 0;
    <span style="color: #008080;">Int64</span> overallListLinqWhere = 0;
    <span style="color: #008080;">Int32</span> loopMax = 200;

    <span style="color: #0000ff;">for</span> (<span style="color: #008080;">Int32</span> loopCounter = 0; loopCounter &lt; loopMax; loopCounter++)
    {
      <span style="color: #008080;">Holder</span> currentHolder = <span style="color: #0000ff;">new</span> <span style="color: #008080;">Holder</span>();

      TimeRun(currentHolder);
      overallDictionaryContainsKeyTime += currentHolder.DictionaryContainsKeyTime;
      overallDictionaryStraightIndexCheck += currentHolder.DictionaryStraightIndexCheck;
      overallListContains += currentHolder.ListContains;
      overallListLinqAny += currentHolder.ListLinqAny;
      overallListLinqFirst += currentHolder.ListLinqFirst;
      overallListLinqWhere += currentHolder.ListLinqWhere;
    }

    Assert.IsTrue
    (
      <span style="color: #0000ff;">false</span>,
      <span style="color: #800000;">" Dictionary_ContainsKey: "</span> + (overallDictionaryContainsKeyTime / loopMax) +
      <span style="color: #800000;">" Dictionary_StraightIndexCheck: "</span> + (overallDictionaryStraightIndexCheck / loopMax) +
      <span style="color: #800000;">" List_Contains: "</span> + (overallListContains / loopMax) +
      <span style="color: #800000;">" List_LinqAny: "</span> + (overallListLinqAny / loopMax) +
      <span style="color: #800000;">" List_LinqFirst: "</span> + (overallListLinqFirst / loopMax) +
      <span style="color: #800000;">" List_LinqWhere: "</span> + (overallListLinqWhere / loopMax)
    );
  }</pre>
<p>And the holder class which is a nothing class. I just didn&#8217;t care for having to add parameters to the child mehod.</p>
<pre>  <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> Holder
  {
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>DictionaryContainsKeyTime { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>DictionaryStraightIndexCheck { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListLinqAny { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListContains { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListLinqFirst { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
    <span style="color: #0000ff;">public</span> <span style="color: #008080;">Int64</span>ListLinqWhere { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }
  }</pre>
<p>Couple Notes:</p>
<ul>
<li>StopWatch is in System.Diagnostics</li>
<li>RandomTool is actual a class of mine. Nothing special about it. Just makes a string of X length with all random letters.</li>
<li>This can not be rebroadcast or retransmitted without the express written permission of my mom.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paging and the Entity Framework, Skip, and Take Part 3</title>
		<link>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/</link>
		<comments>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/#comments</comments>
		<pubDate>Fri, 08 May 2009 14:30:50 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[Entity Framework]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Skip]]></category>
		<category><![CDATA[Take]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=635</guid>
		<description><![CDATA[Get the total count of pages. &#124; Get the real page number. &#124; Using Skip and Take to Page &#124; The Actual Paging Controls Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-1">Get the total count of pages.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-2">Get the real page number.</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-3">Using Skip and Take to Page</a> | <a href="http://byatool.com/index.php/uncategorized/paging-and-the-entity-framework-skip-and-take-part-4">The Actual Paging Controls</a></p>
<p>Ok so the last two posts have been arguably useless, maybe more so than anything else here, but they were somewhat needed because now I am going to show how to Linq, the Entity Framework, and well that&#8217;s it I think.</p>
<pre><span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IList&lt;ToolItem&gt;</span> GetSomeTools(<span style="color: #008080;">String</span> name, <span style="color: #008080;">Int32</span> numberToShow, <span style="color: #008080;">Int32</span> pageNumber, <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> realPage, <span style="color: #0000ff;">out</span> <span style="color: #008080;">Int32</span> totalCountOfPages)
{
  <span style="color: #008000;">//EntityContext.Context is just a </span><a href="http://byatool.com/index.php/lessons/entity-framework-objectcontext-observations-on-caching"><span style="color: #008000;">singletonish version</span></a><span style="color: #008000;"> of the
  //Entities class.  Most people would use
  //  using (ToolEntities context = new ToolEnties())
</span>  <span style="color: #008080;">Int32</span> totalCount = EntityContext.Context.ToolItems
		   .Count(item =&gt; item.Name == name);
  <span style="color: #008000;">//This is the method from the first post of this series
  //Just getting the count of pages based on numberToShow and
  //item totalCount</span>
  totalCountOfPages = TotalCountOfPages(totalCount, numberToShow);
  <span style="color: #008000;">//This is the method from the second post of this series
  //Basically getting the best possible page if the page number
  //is higher than the totalCountOfPages or lower than 0</span>
  realPage = GetRealPage(totalCountOfPages, pageNumber);

  returnValue = EntityContext.Context.ChatRooms
			  .Where(item =&gt; item.Name == name )
			  .OrderBy(item =&gt; item.Name)
			  .Skip(numberToShow * realPage)
			  .Take(numberToShow)
			  .ToList();

  <span style="color: #0000ff;">return</span> returnValue.ToList();
}</pre>
<p>Really simple yes? It follows like this:</p>
<p>Say I&#8217;m on page 1, which for this would be zero or pageNumber &#8211; 1. So I want to grab the first 20 items from the database. Well that means I want to start at 0 and grab 20. Now if you want this all to be done with some kind of conditional thing that either handles the first page or the other pages, you actually want to skip the same way no matter what the page number is. This is taken care of by numberToShow * realPage since even at 0 this works. After all 0 * anything is 0 and therefore you will be Skipping 0 items. So in other words, you&#8217;re at the start. Next you want to Take the amount of items you need, which is 20. Next time around you&#8217;ll start at 20 Skip(numberToShow 20 * realPage 1) and take the next 20. Nice thing is, even if you say Take 20 and there are only 2 left, it doesn&#8217;t care. It will just grab those two.</p>
<p>And there you have it, how to page with the Entity Framework and minimal amount of work. I know I hate taking other people&#8217;s methods (Like the TotalCountOfPages and GetRealPage methods), don&#8217;t know why. So sorry if I am forcing you to do so. However, the two methods I gave are semi important to this.</p>
<p>You might wonder why realPage and totalCountOfPages, well this is useful stuff when knowing what page is next for paging controls.  Next post I&#8217;ll show those off but I&#8217;ll warn you, they are nothing spectacular.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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&#8217;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&#8217;t look right. Now with [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;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&#8217;t look right.</p>
<p>Now with most of the Linq methods like Where or First, it&#8217;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&#8217;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 &#8220;Give me the stupid key on the Outer (User) list that I should care about.&#8221;</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&#8230;say what? Ok this may look weird at first but you&#8217;ll hate yourself for not seeing it. It&#8217;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&#8217;t just chain them together and have it remember every list you&#8217;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&#8217;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>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/c/linq-join-method-and-how-to-use-it/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Use Linq to Split a List: Skip and Take</title>
		<link>http://byatool.com/general-coding/use-linq-to-split-a-list-skip-and-take/</link>
		<comments>http://byatool.com/general-coding/use-linq-to-split-a-list-skip-and-take/#comments</comments>
		<pubDate>Wed, 22 Apr 2009 16:56:56 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[List]]></category>
		<category><![CDATA[Skip]]></category>
		<category><![CDATA[Take]]></category>

		<guid isPermaLink="false">http://byatool.com/?p=600</guid>
		<description><![CDATA[Say what? Ok this is simple, and probably useless for most people but I thought I&#8217;d post it anyhow. Basically, say you have a huge list of something and you need to split it into smaller lists of something. This might be the case if you want to use parameterized SQL or something like HQL [...]]]></description>
			<content:encoded><![CDATA[<p>Say what? Ok this is simple, and probably useless for most people but I thought I&#8217;d post it anyhow. Basically, say you have a huge list of something and you need to split it into smaller lists of something. This might be the case if you want to use parameterized SQL or something like HQL to send in a list full of somethings. Problem? Sql Server will only allow so many parameters to be sent in. Now you could send in a string in some cases, but meh. Kind of sloppy. So what do you do? You come here and you gank this method.</p>
<pre>        <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">static</span> <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">IList</span>&lt;T&gt;&gt; SplitList&lt;T&gt;
          (<span style="color: #008080;">IList</span>&lt;T&gt; listToSplit, <span style="color: #008080;">Int32</span> countToTake)
        {
            <span style="color: #008080;">IList</span>&lt;<span style="color: #008080;">IList</span>&lt;T&gt;&gt; splitList = <span style="color: #0000ff;">new</span> <span style="color: #008080;">List</span>&lt;<span style="color: #008080;">IList</span>&lt;T&gt;&gt;();
            <span style="color: #008080;">Int32</span> countToSkip = 0;

            <span style="color: #0000ff;">do</span>
            {
                splitList.Add(listToSplit.Skip(countToSkip)
                 .Take(countToTake).ToList());
                countToSkip += countToTake;
            } <span style="color: #0000ff;">while</span> (countToSkip &lt; listToSplit.Count);

            <span style="color: #0000ff;">return</span> splitList;
        }</pre>
<p>Pretty simple. It takes in a list of whatever and gives you back a list of lists of whatever. The fun part is using Skip and Take. Two methods I have come to love.</p>
<p>Basically you start out <span class="showItLink" xmlns:comment="Since it's the start.">skipping nothing</span> and taking a set amount&#8230; say 2000. Next time through, you start by skipping 2000 and taking the next 2000. Beauty of Take is it won&#8217;t just die on you if you don&#8217;t have enough items. It&#8217;ll just grab what&#8217;s left. Yay for take.</p>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/use-linq-to-split-a-list-skip-and-take/feed/</wfw:commentRss>
		<slash:comments>1</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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;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>
]]></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&#8217;t infer the return type of the method. Wait what? It&#8217;s pretty obvious right, it&#8217;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 &#8220;typed&#8221; also. Well here&#8217;s the problem (And you&#8217;re dumb for not knowing this, but I&#8217;m not because I&#8217;m immune to dumb), ReturnNumber isn&#8217;t a method, it&#8217;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&#8217;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&#8217;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&#8217;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&#8217;t.  So basically you&#8217;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>
]]></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>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&#8217;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&#8217;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&#8217;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&#8217;ll see the code amount differing more and more.</p>
<p>I realize this isn&#8217;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>
]]></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&#8217;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&#8217;s a matter of preference, but the first seems way too verbose for something too simple.</p>
]]></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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;ve used both Func fields and methods to return Funcs to clean up how this would look. I&#8217;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&#8217;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>
]]></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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;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&#8217;t have to use as much reflection everytime. I just didn&#8217;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>
]]></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&#8217;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&#8217;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&#8217;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>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/more-fun-with-linq/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&#8217;t heard of the FizzBuzz test, it&#8217;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&#8217;t heard of the FizzBuzz test, it&#8217;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&#8217;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&#8217;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>
]]></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>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&#8217;t it&#8217;s ok. Most likely you&#8217;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 &#8220;in other words&#8221; 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&#8217;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&#8217;t adamant about wanting Covariance in parameters, this can&#8217;t happen.</p>
<p>Well shoot, I just gave away the fun of this post. Oh well, I&#8217;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>
]]></content:encoded>
			<wfw:commentRss>http://byatool.com/lessons/and-now-for-contravariance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

