﻿<?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>Whelps! Left Side! Left Side! Minus 50 DKP!</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>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'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'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'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'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't actually care about the attached value? I'm sure I'm breaking a rule somewhere... 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'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'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'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'm lazy)</p>
<p>What did I find out? Well if it didn'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'm on track. As for looks? That'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'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>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/how-to-use-a-factory-method-with-castle-windsorcontainer/" title="How to Use a Factory Method With Castle / WindsorContainer">How to Use a Factory Method With Castle / WindsorContainer</a></li><li><a href="http://byatool.com/lessons/castle-rhino-mocking-and-possibly-you/" title="Castle, Rhino, Mocking, and Possibly You">Castle, Rhino, Mocking, and Possibly You</a></li><li><a href="http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/" title="Paging and the Entity Framework, Skip, and Take Part 3">Paging and the Entity Framework, Skip, and Take Part 3</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/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'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'm on page 1, which for this would be zero or pageNumber - 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're at the start. Next you want to Take the amount of items you need, which is 20. Next time around you'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'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's methods (Like the TotalCountOfPages and GetRealPage methods), don'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'll show those off but I'll warn you, they are nothing spectacular.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/use-linq-to-split-a-list-skip-and-take/" title="Use Linq to Split a List: Skip and Take">Use Linq to Split a List: Skip and Take</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-set-up-complex-types-now-with-more-poco/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO">.Net 4.0 Beta 2 Entity Framework &#8211; How To Set Up Complex Types, Now With More POCO</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-many-to-one-and-poco-insert-statement-conflicted-with-the-foreign-key-constraint-issue/" title=".Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue">.Net 4.0 Beta 2 Entity Framework &#8211; Many To One and POCO / INSERT statement conflicted with the FOREIGN KEY constraint issue</a></li><li><a href="http://byatool.com/lessons/net-4-0-beta-2-entity-framework-how-to-start/" title=".Net 4.0 Beta 2 Entity Framework &#8211; How To Start">.Net 4.0 Beta 2 Entity Framework &#8211; How To Start</a></li></ul>]]></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'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>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'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'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... say 2000. Next time through, you start by skipping 2000 and taking the next 2000. Beauty of Take is it won't just die on you if you don't have enough items. It'll just grab what's left. Yay for take.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/" title="Paging and the Entity Framework, Skip, and Take Part 3">Paging and the Entity Framework, Skip, and Take Part 3</a></li><li><a href="http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/" title="Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match">Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match</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><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/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'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>Uhg It Won&#8217;t End</title>
		<link>http://byatool.com/general-coding/uhg-it-wont-end/</link>
		<comments>http://byatool.com/general-coding/uhg-it-wont-end/#comments</comments>
		<pubDate>Fri, 10 Oct 2008 17:22:58 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dynamic]]></category>
		<category><![CDATA[Func]]></category>
		<category><![CDATA[Lambda]]></category>
		<category><![CDATA[Linq]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  propertyList = GetInfo(item);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/22/like-versus-contains/</guid>
		<description><![CDATA[So have to figure this one out. Say you have: private static Expression&#60;Func&#60;User, Boolean&#62;&#62; WhereLikeFirstNameLastNameUserName(String name) { return currentUser =&#62; SqlMethods.Like(currentUser.UserName, "%" + name + "%") &#124;&#124; SqlMethods.Like(currentUser.FirstName, "%" + name + "%") &#124;&#124; SqlMethods.Like(currentUser.LastName, "%" + name + "%"); } And private static Expression &#60;Func&#60;User, Boolean&#62;&#62; WhereLikeFirstNameLastNameUserNameWithoutLike(String name) { return currentUser =&#62; currentUser.UserName.Contains(name) &#124;&#124; [...]]]></description>
			<content:encoded><![CDATA[<p>So have to figure this one out. Say you have:</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>And</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; WhereLikeFirstNameLastNameUserNameWithoutLike(<span style="color: #00cccc;">String </span>name)
{
  <span style="color: #3333ff;">return </span>currentUser =&gt; currentUser.UserName.Contains(name)
  || currentUser.FirstName.Contains(name)
  || currentUser.LastName.Contains(name);
}</pre>
<p>The first one should look familiar, its part of the "dynamic" linq stuff I've been posting. Now guess which one gives me this SQL when profiled:</p>
<pre><span style="color: #3333ff;">exec </span><span style="color: #660000;">sp_executesql</span> N
<span style="color: #ff0000;">'SELECT</span>
<span style="color: #ff0000;"> [t0].[UserID],</span>
<span style="color: #ff0000;"> [t0].[FirstName],</span>
<span style="color: #ff0000;"> [t0].[LastName],</span>
<span style="color: #ff0000;"> [t0].[Password],</span>
<span style="color: #ff0000;"> [t0].[UserName],</span>
<span style="color: #ff0000;"> [t0].[UserTypeID]</span>
<span style="color: #ff0000;">FROM</span>
<span style="color: #ff0000;"> [dbo].[User] AS [t0]</span>
<span style="color: #ff0000;">WHERE</span>
<span style="color: #ff0000;"> ([t0].[UserName] LIKE @p0)</span>
<span style="color: #ff0000;">OR</span>
<span style="color: #ff0000;"> ([t0].[FirstName] LIKE @p1)</span>
<span style="color: #ff0000;">OR</span>
<span style="color: #ff0000;"> ([t0].[LastName] LIKE @p2)</span>
<span style="color: #ff0000;">ORDER BY</span>
<span style="color: #ff0000;"> [t0].[UserName]'</span>,

N<span style="color: #ff0000;">'@p0 varchar(3),</span>
<span style="color: #ff0000;"> @p1 nvarchar(3),</span>
<span style="color: #ff0000;"> @p2 nvarchar(3)'</span>,
 @p0=<span style="color: #ff0000;">'%s%'</span>,
 @p1=N<span style="color: #ff0000;">'%s%'</span>,
 @p2=N<span style="color: #ff0000;">'%s%'</span></pre>
<p>If you answered both, you are correct or you looked ahead for the answer and therefore are a tool. Now which do you think that...</p>
<pre>query.ToList()</pre>
<p>Produces the correct list? If you answered Contains, then you are correct again. If you are a tool, you probably looked ahead again...</p>
<p>Why is this? I HAVE NO IDEA... Something I have to look into for sure.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/linq-extension-methods-versus-linq-query-language-deathmatch/" title="Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH">Linq Extension Methods Versus Linq Query Language&#8230; DEATHMATCH</a></li><li><a href="http://byatool.com/general-coding/uhg-it-wont-end/" title="Uhg It Won&#8217;t End">Uhg It Won&#8217;t End</a></li><li><a href="http://byatool.com/pontification/what-is-readable-addon/" title="What Is Readable Addon">What Is Readable Addon</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/net-issues/like-versus-contains/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Backtrack</title>
		<link>http://byatool.com/pontification/backtrack/</link>
		<comments>http://byatool.com/pontification/backtrack/#comments</comments>
		<pubDate>Fri, 18 Jul 2008 17:46:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Pontification]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[OrderBy]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/18/backtrack/</guid>
		<description><![CDATA[Couple posts ago I said "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." when I was talking about how to create an order by [...]]]></description>
			<content:encoded><![CDATA[<p>Couple posts ago I said "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." when I was talking about how to create an order by expression. I thought about it more, and that doesn't make sense as far as the sql goes. What I was saying would mean it would get the list of strings and sort based on them. What I think actually happens is it takes the Expression (Hense the name) and derives the order by from the epression.</p>
<p>Say I want tell the thing I will want to sort by user.UserName, it will take that expression and translate it into ORDER BY someAlias.UserName. Magic. I would like to know how it does this. Reflection and a ton of it I would assume.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/dictionary-index-lookup-vs-contains-key-vs-list-contains-vs-linq-speed-testtexas-tornado-match/" title="Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match">Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq&#8230; Speed Test/Texas Tornado Match</a></li><li><a href="http://byatool.com/utilities/paging-and-the-entity-framework-skip-and-take-part-3/" title="Paging and the Entity Framework, Skip, and Take Part 3">Paging and the Entity Framework, Skip, and Take Part 3</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><li><a href="http://byatool.com/general-coding/use-linq-to-split-a-list-skip-and-take/" title="Use Linq to Split a List: Skip and Take">Use Linq to Split a List: Skip and Take</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/pontification/backtrack/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I&#8217;m starting to worry about myself</title>
		<link>http://byatool.com/general-coding/im-starting-to-worry-about-myself/</link>
		<comments>http://byatool.com/general-coding/im-starting-to-worry-about-myself/#comments</comments>
		<pubDate>Fri, 18 Jul 2008 17:22: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[Expression]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/18/im-starting-to-worry-about-myself/</guid>
		<description><![CDATA[So the "dynamic" linq query so far isn't just enough to stop. Oh no, now that I can have methods pass back expressions, what about a dictionary of order by expressions to allow an even more dynamic feel? Huh? How's about that kids? I hate myself too. //Enum created for the dictionary key public enum [...]]]></description>
			<content:encoded><![CDATA[<p>So the "dynamic" linq query so far isn't just enough to stop. Oh no, now that I can have methods pass back expressions, what about a dictionary of order by expressions to allow an even more dynamic feel? Huh? How's about that kids? I hate myself too.</p>
<pre><span style="color: #009900;">//Enum created for the dictionary key</span>
<span style="color: #3333ff;">public enum</span> <span style="color: #00cccc;">OrderByChoice</span>
{
  FirstName,
  LastName,
  UserName
}

<span style="color: #009900;">//dictionary of expressions</span>
<span style="color: #3333ff;">private static</span> <span style="color: #00cccc;">Dictionary</span>&lt;<span style="color: #000000;"><span style="color: #00cccc;">OrderByChoice</span>, </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;&gt;  GetOrderByList()
{
<span style="color: #3333ff;">  if</span>(orderByList == <span style="color: #3333ff;">null</span>)
  {
    orderByList = <span style="color: #3333ff;">new</span> <span style="color: #00cccc;">Dictionary</span>&lt;OrderByChoice,<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;&gt;();

    orderByList.Add(<span style="color: #00cccc;">OrderByChoice</span>.FirstName, currentUser =&gt; currentUser.FirstName);
    orderByList.Add(<span style="color: #00cccc;">OrderByChoice</span>.LastName, currentUser =&gt; currentUser.LastName);
    orderByList.Add(<span style="color: #00cccc;">OrderByChoice</span>.UserName, currentUser =&gt; currentUser.UserName);
  }

<span style="color: #3333ff;">  return </span>orderByList;
}</pre>
<p>That's right, I know. Silly, but I think it's cool. Now mind you, I could have methods that return expressions instead of the expressions themselves, but I wanted to show the expressions.</p>
<p>And for the method call:</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">IList</span>&lt;<span style="color: #00cccc;">User</span>&gt;<span style="color: #00cccc;"> </span>GetUserList(<span style="color: #00cccc;">OrderByChoice </span>orderBy)
{
<span style="color: #00cccc;">  <span style="color: #3333ff;">return </span></span>GetUserList(currentUser =&gt; <span style="color: #3333ff;">true</span>, GetOrderByList()[orderBy]).ToList();
}</pre>
<p>And now you have an even more dynamicish call.</p>
<p>I FORGOT THE USINGS!!!!</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/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/orderby-using-a-property-name/" title="Dynamic Linq: OrderBy Using a String for a Property Name">Dynamic Linq: OrderBy Using a String for a Property Name</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/im-starting-to-worry-about-myself/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>Convert a String to a Number String With Linq&#8230; YAY</title>
		<link>http://byatool.com/utilities/quick-linq-thing-string-to-number-string/</link>
		<comments>http://byatool.com/utilities/quick-linq-thing-string-to-number-string/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 19:22:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[Utilities]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/17/quick-linq-thing-string-to-number-string/</guid>
		<description><![CDATA[Really stupid little thing I came up with today... but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing. public static String CreateNumberOnlyString(String textToCheck) { String returnText; var queryForIntegers = from currentChar in textToCheck where [...]]]></description>
			<content:encoded><![CDATA[<p>Really stupid little thing I came up with today... but I wanted to use Linq to strip any non number from a string and return the string with only numbers. I told you this was a stupid little thing.</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">String </span>CreateNumberOnlyString(<span style="color: #00cccc;">String </span>textToCheck)
{
  <span style="color: #00cccc;">String </span>returnText;

  <span style="color: #3333ff;">var </span>queryForIntegers = <span style="color: #3333ff;">from </span>currentChar <span style="color: #3333ff;">in </span>textToCheck
                         <span style="color: #3333ff;">where </span>Char.IsNumber(currentChar)
                         <span style="color: #3333ff;">select </span>currentChar;

  returnText = <span style="color: #3333ff;">new </span>String(queryForIntegers.ToArray());

  <span style="color: #3333ff;">return </span>returnText;
}</pre>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/c/i-are-tupid/" title="I are tupid">I are tupid</a></li><li><a href="http://byatool.com/pointless/state-list-in-dictionary-form/" title="State List in Dictionary Form">State List in Dictionary Form</a></li><li><a href="http://byatool.com/general-coding/by-reference-in-c-and-how-to-get-schooled-by-it/" title="By Reference in C# and How to Get Schooled By It">By Reference in C# and How to Get Schooled By It</a></li><li><a href="http://byatool.com/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/utilities/quick-linq-thing-string-to-number-string/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>Sub Select and IN Clause With Linq</title>
		<link>http://byatool.com/general-coding/sub-select-and-in-clause-faking/</link>
		<comments>http://byatool.com/general-coding/sub-select-and-in-clause-faking/#comments</comments>
		<pubDate>Wed, 09 Jul 2008 16:59:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Clause]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Select]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/09/sub-select-and-in-clause-faking/</guid>
		<description><![CDATA[I have yet to find a good way to represent an IN clause in Linq, but I found this yesterday and kind of liked it. Mind you, I've used this only on two lists, not database involved. Will check what it does on the database call later. Anyhow, I needed a way to check if [...]]]></description>
			<content:encoded><![CDATA[<p>I have yet to find a good way to represent an IN clause in Linq, but I found this yesterday and kind of liked it. Mind you, I've used this only on two lists, not database involved. Will check what it does on the database call later.</p>
<p>Anyhow, I needed a way to check if the records in one list are the same as the other. I'm sure there are a billion ways to do this, but I wanted a Linq way. I stumbled onto this idea when looking for a solution to something else. Basically I have two lists of users and a user contains a UserID. listOne and listTwo are both <span style="color: #3333ff;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt;.</p>
<pre><span style="color: #3333ff;">var</span> query = <span style="color: #3333ff;">from</span> listOneUser <span style="color: #3333ff;">in</span> listOne
            <span style="color: #3333ff;">where</span>
            !(
                <span style="color: #3333ff;">from</span> listTwoUser <span style="color: #3333ff;">in</span> listTwo
                <span style="color: #3333ff;">select</span> listTwoUser.UserID
            ).Contains(listOneUser.UserID)
              <span style="color: #3333ff;">select</span> listOneUser;</pre>
<p>I select all the IDs from the second list and then see if the first list has any users that don't exist in the second list. If this query gives me a list with a count greater then 0, I know that list one has at least one different item. Again, this isn't bullet proof, just a way to show the kind of IN clause.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/lessons/and-then-you-hit-the-wall/" title="And then you hit the wall.">And then you hit the wall.</a></li><li><a href="http://byatool.com/general-coding/when-is-a-field-not-a-field/" title="When is a field not a field?">When is a field not a field?</a></li><li><a href="http://byatool.com/general-coding/adding-to-the-select/" title="Adding to the Select">Adding to the Select</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/general-coding/sub-select-and-in-clause-faking/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Join By Anonymous Types in Linq</title>
		<link>http://byatool.com/general-coding/joining-by-anonymous-types/</link>
		<comments>http://byatool.com/general-coding/joining-by-anonymous-types/#comments</comments>
		<pubDate>Wed, 09 Jul 2008 13:20:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Anonymous Types]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Join]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/09/joining-by-anonymous-types/</guid>
		<description><![CDATA[Just found this out yesterday so I thought I would post and pass on to all two of you reading this. Suppose you have a User table and a Contacts table and you wanted to find all the users that match up with the contacts table. Now suppose there is no direct correlation. What to [...]]]></description>
			<content:encoded><![CDATA[<p>Just found this out yesterday so I thought I would post and pass on to all two of you reading this.</p>
<p>Suppose you have a User table and a Contacts table and you wanted to find all the users that match up with the contacts table. Now suppose there is no direct correlation. What to do? You could do something really brilliant by joining the tables together on FirstName and LastName, because we all know that there will always only be one John Smith in either table. Screw you, I couldn't think of a better example at the time.</p>
<pre><span style="color: #3333ff;">public static</span> <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt; GetAllUsersWithMatchingContactInformationUsingJoin()
{
  <span style="color: #3333ff;">List</span>&lt;<span style="color: #00cccc;">User</span>&gt; foundUsers;

  <span style="color: #3333ff;">var</span> query = <span style="color: #3333ff;">from</span> user <span style="color: #3333ff;">in</span> dataContext.Users
              <span style="color: #3333ff;">join </span>contact in dataContext.Contacts <span style="color: #3333ff;">on new</span> {user.FirstName, user.LastName } <span style="color: #3333ff;">equals new</span> { contact.FirstName, contact.LastName }
              select user;

              foundUsers = query.ToList();

  <span style="color: #3333ff;">return</span> foundUsers;
}</pre>
<p>As you can see here:</p>
<pre><span style="color: #3333ff;">join </span>contact <span style="color: #3333ff;">in</span> dataContext.Contacts <span style="color: #3333ff;">on new</span> {user.FirstName, user.LastName } <span style="color: #3333ff;">equals new</span> { contact.FirstName, contact.LastName }</pre>
<p>You can create a type on the fly and then compare it to another. I thought that was interesting.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/lessons/and-then-you-hit-the-wall/" title="And then you hit the wall.">And then you hit the wall.</a></li><li><a href="http://byatool.com/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/pontification/c-var-and-objec-propert-i-have-no-idea-what-the-term-is/" title="C#, Var, and Objec-  Propert-  I have no idea what the term is">C#, Var, and Objec-  Propert-  I have no idea what the term is</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/joining-by-anonymous-types/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I are tupid</title>
		<link>http://byatool.com/c/i-are-tupid/</link>
		<comments>http://byatool.com/c/i-are-tupid/#comments</comments>
		<pubDate>Mon, 07 Jul 2008 18:58:00 +0000</pubDate>
		<dc:creator>Sean</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[General Coding]]></category>
		<category><![CDATA[Linq]]></category>
		<category><![CDATA[Order By]]></category>
		<category><![CDATA[Select]]></category>
		<category><![CDATA[Stupid]]></category>

		<guid isPermaLink="false">http://rockcityghost.wordpress.com/2008/07/07/i-are-tupid/</guid>
		<description><![CDATA[This may be novel or really dumb, but I like it. Say you want to convert a Dictionary to a List of KeyValuePairs that are sorted by something within the dictionary Key or Value. Don't ask why, just go with it. You could do this: Where someDictionary is Dictionary&#60;Type, string&#62; : List&#60;KeyValuePair&#60;Type, String&#62;&#62; dataSource = [...]]]></description>
			<content:encoded><![CDATA[<p>This may be novel or really dumb, but I like it. Say you want to convert a Dictionary to a List of KeyValuePairs that are sorted by something within the dictionary Key or Value. Don't ask why, just go with it. You could do this:</p>
<p>Where someDictionary is Dictionary&lt;Type, string&gt; :</p>
<pre>
<span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">KeyValuePair</span>&lt;<span style="color: #00cccc;">Type</span>, <span style="color: #00cccc;">String</span>&gt;&gt; dataSource = new <span style="color: #00cccc;">List</span>&lt;<span style="color: #00cccc;">KeyValuePair</span>&lt;<span style="color: #00cccc;">Type</span>, <span style="color: #00cccc;">String</span>&gt;&gt;(someDictionary);
dataSource.Sort(<span style="color: #3333ff;">new </span><span style="color: #00cccc;">SomeComparer</span>&lt;<span style="color: #00cccc;">KeyValuePair</span>&lt;<span style="color: #00cccc;">Type</span>, <span style="color: #00cccc;">String</span>&gt;&gt;(<span style="color: #ff0000;">"Value"</span>, <span style="color: #3333ff;">true</span>));</pre>
<p>To:</p>
<pre><span style="color: #3366ff;">var</span> query = <span style="color: #3333ff;">from </span>keyValuePair <span style="color: #3333ff;">in</span> someDictionary
          <span style="color: #3333ff;">orderby </span>keyValuePair.Value
          <span style="color: #3333ff;">select new </span><span style="color: #00cccc;">KeyValuePair</span>&lt;<span style="color: #00cccc;">Type</span>, <span style="color: #3333ff;">String</span>&gt;(keyValuePair.Key, keyValuePair.Value);
SomeMethod(query.ToList());</pre>
<p>If nothing else, you don't have to create or implement a System.Collections.IComparer class to use the .Sort method. That seems worth it. That and I think it just plain looks better, but that just me. If I am completely wrong here, refer to the title of this post. Just a thought really.</p>
<div  class="related_post_title">Related Posts</div><ul class="related_post"><li><a href="http://byatool.com/general-coding/when-is-a-field-not-a-field/" title="When is a field not a field?">When is a field not a field?</a></li><li><a href="http://byatool.com/general-coding/adding-to-the-select/" title="Adding to the Select">Adding to the Select</a></li><li><a href="http://byatool.com/pontification/what-is-readable/" title="What Is Readable">What Is Readable</a></li><li><a href="http://byatool.com/general-coding/orderby-using-a-property-name/" title="Dynamic Linq: OrderBy Using a String for a Property Name">Dynamic Linq: OrderBy Using a String for a Property Name</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://byatool.com/c/i-are-tupid/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>
	</channel>
</rss>
