<?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>.Net Smoothie &#187; LINQ</title>
	<atom:link href="http://www.richardbushnell.net/tag/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.richardbushnell.net</link>
	<description></description>
	<lastBuildDate>Wed, 30 Dec 2009 11:42:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Design Guidelines for LINQ</title>
		<link>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/</link>
		<comments>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 18:40:24 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Guidelines]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/13/design-guidelines-for-linq/</guid>
		<description><![CDATA[Have you wondered if and when you should use the new LINQ features in .Net 3.5? Like, where should I put a new extension method? Should I use Func&#60;T&#62; or a custom delegate? How do I best implement a mix-in (extension methods on an interface)? Well, Mircea Trofin has just published a new draft of [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F13%2Fdesign-guidelines-for-linq%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Have you wondered if and when you should use the new LINQ features in .Net 3.5?</p>
<p>Like, where should I put a new extension method? Should I use Func&lt;T&gt; or a custom delegate? How do I best implement a mix-in (extension methods on an interface)?</p>
<p>Well, Mircea Trofin has just published a new draft of some <a href="http://blogs.msdn.com/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx" target="_blank">LINQ design guidelines</a>. You might just find your answers there.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F13%2Fdesign-guidelines-for-linq%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Update Data with LINQ-to-SQL</title>
		<link>http://www.richardbushnell.net/2008/02/18/how-to-update-data-with-linq-to-sql/</link>
		<comments>http://www.richardbushnell.net/2008/02/18/how-to-update-data-with-linq-to-sql/#comments</comments>
		<pubDate>Mon, 18 Feb 2008 17:50:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[LINQ to SQL]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/18/how-to-update-data-with-linq-to-sql/</guid>
		<description><![CDATA[When learning LINQ-to-SQL, it&#8217;s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the DataContext and then calling SubmitChanges on the context. var product = (from p in dataContext.Products where p.ProductID == 1 select p).Single(); [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F18%2Fhow-to-update-data-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>When learning LINQ-to-SQL, it&#8217;s not immediately obvious how to do an update. Querying is easy, and there are methods for inserting and deleting. Updating usually occurs by modifying an object already known to the <strong>DataContext</strong> and then calling <strong>SubmitChanges</strong> on the context.</p>
<blockquote><pre class="code"><span style="color: blue">var </span>product = (<span style="color: blue">from </span>p <span style="color: blue">in </span>dataContext.Products
               <span style="color: blue">where </span>p.ProductID == 1
               <span style="color: blue">select </span>p).Single();

product.Name = <span style="color: #a31515">&quot;Richard's product&quot;</span>;

dataContext.SubmitChanges();</pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>It&#8217;s nice to see that MSDN documentation actually addresses the obvious arising question:</p>
<blockquote>
<p>Q. Can I update table data without first querying the database?</p>
<p>A. Although LINQ to SQL does not have set-based update commands, you can use either of the following techniques to update without first querying:</p>
<ul>
<li>Use ExecuteCommand to send SQL code. </li>
<li>Create a new instance of the object and initialize all the current values (fields) that affect the update. Then attach the object to the DataContext by using Attach and modify the field you want to change. </li>
</ul>
</blockquote>
<p><span id="more-54"></span></p>
<p>If you ask me, using an <strong>ExecuteCommand </strong>defeats the object of LINQ-to-SQL. After all, we&#8217;re using it as a data-access-layer to generate entities in code based on the data schema. The last thing we want to have to do is start writing strings of SQL.</p>
<p>So that&#8217;s out.</p>
<h3>I&#8217;m So Attached</h3>
<p>The second option is to use the <strong>Attach</strong> method on the table we&#8217;re updating. I&#8217;ve tried to use the <strong>Attach </strong>method before, but it didn&#8217;t work.</p>
<p>To see what I mean, try this in LINQPad (using the AdventureWorks database from CodePlex):</p>
<blockquote>
<pre class="code"><span style="color: blue">var </span><span style="color: black">product = </span><span style="color: blue">new </span><span style="color: black">Product();
product.ProductID = </span><span style="color: #c81efa">1</span><span style="color: black">;
product.Name = </span><span style="color: #dc1414">&quot;Richard's product&quot;</span><span style="color: black">;

Products.Attach(product);

</span><span style="color: blue">var </span><span style="color: black">changeSet = GetChangeSet();

changeSet.Dump();</span></pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You&#8217;ll see that there are no changes to make, so no updates are made.</p>
<p>Now, move the line of code that does the update after the call to <strong>Attach</strong>, so as to attach the product first before updating the field:</p>
<blockquote>
<pre class="code"><span style="color: blue">var </span><span style="color: black">product = </span><span style="color: blue">new </span><span style="color: black">Product();
product.ProductID = </span><span style="color: #c81efa">1</span><span style="color: black">;

Products.Attach(product);
</span><span style="color: black">
//Notice we're doing this laterproduct.Name = </span><span style="color: #dc1414">&quot;Richard's product&quot;</span><span style="color: black">;

</span><span style="color: blue">var </span><span style="color: black">changeSet = GetChangeSet();

changeSet.Dump();</span></pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The c<strong>hangeset</strong> now shows that one update is ready to be made. Unfortunately, if you call <strong>SubmitChanges</strong>, you get an exception:</p>
<blockquote>
<pre class="code">SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.</pre>
</blockquote>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The MSDN documentation isn&#8217;t so clear here. What do we need to set to get it to work?</p>
<p>The SQL being sent to the database is instructive:</p>
<blockquote>
<pre class="code"><span style="color: blue">UPDATE </span>[Production]<span style="color: gray">.</span>[Product]
<span style="color: blue">SET </span>[Name] <span style="color: gray">= </span>@p9
<span style="color: blue">WHERE </span><span style="color: gray">(</span>[ProductID] <span style="color: gray">= </span>@p0<span style="color: gray">) AND (</span>[Name] <span style="color: gray">IS NULL)
AND (</span>[ProductNumber] <span style="color: gray">IS NULL)
AND (NOT (</span>[MakeFlag] <span style="color: gray">= </span>1<span style="color: gray">))
AND (NOT (</span>[FinishedGoodsFlag] <span style="color: gray">= </span>1<span style="color: gray">))
AND (</span>[Color] <span style="color: gray">IS NULL)
AND (</span>[SafetyStockLevel] <span style="color: gray">= </span>@p1<span style="color: gray">)
AND (</span>[ReorderPoint] <span style="color: gray">= </span>@p2<span style="color: gray">)
AND (</span>[StandardCost] <span style="color: gray">= </span>@p3<span style="color: gray">)
AND (</span>[ListPrice] <span style="color: gray">= </span>@p4<span style="color: gray">)
AND (</span>[Size] <span style="color: gray">IS NULL)
AND (</span>[SizeUnitMeasureCode] <span style="color: gray">IS NULL)
AND (</span>[WeightUnitMeasureCode] <span style="color: gray">IS NULL)
AND (</span>[Weight] <span style="color: gray">IS NULL)
AND (</span>[DaysToManufacture] <span style="color: gray">= </span>@p5<span style="color: gray">)
AND (</span>[ProductLine] <span style="color: gray">IS NULL)
AND (</span>[Class] <span style="color: gray">IS NULL)
AND (</span>[Style] <span style="color: gray">IS NULL)
AND (</span>[ProductSubcategoryID] <span style="color: gray">IS NULL)
AND (</span>[ProductModelID] <span style="color: gray">IS NULL)
AND (</span>[SellStartDate] <span style="color: gray">= </span>@p6<span style="color: gray">)
AND (</span>[SellEndDate] <span style="color: gray">IS NULL)
AND (</span>[DiscontinuedDate] <span style="color: gray">IS NULL)
AND (</span>[rowguid] <span style="color: gray">= </span>@p7<span style="color: gray">)
AND (</span>[ModifiedDate] <span style="color: gray">= </span>@p8<span style="color: gray">)
</span><span style="color: green">-- @p0: Input Int (Size = 0; Prec = 0; Scale = 0) [1]
-- @p1: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [0]
-- @p2: Input SmallInt (Size = 0; Prec = 0; Scale = 0) [0]
-- @p3: Input Decimal (Size = 0; Prec = 29; Scale = 4) [0]
-- @p4: Input Decimal (Size = 0; Prec = 29; Scale = 4) [0]
-- @p5: Input Int (Size = 0; Prec = 0; Scale = 0) [0]</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
</blockquote>
<p>The problem is now that LINQ-to-SQL tables automatically use optimistic concurrency, and for some reason (maybe only in LINQPad) the SellStartDate is not set, and neither are the rowguid or ModifiedDate fields. In any case, either we have to turn off optimistic concurrency, or set all the field values ourselves.</p>
<h3>Using Optimistic Concurrency with Updates</h3>
<p>Unfortunately, by default all fields are used for optimistic concurrency, so you have to set values for all fields. If you were using ASP.Net you could keep a copy of the variables in the session state or something, but at least it saves you a round trip to the database.</p>
<p>Here&#8217;s the code that actually does perform an update:</p>
<blockquote>
<pre class="code"><span style="color: blue">var </span>product = <span style="color: blue">new </span><span style="color: #2b91af">Product</span>();
product.ProductID = 1;
product.Name = <span style="color: #a31515">&quot;Adjustable Race&quot;</span>;
product.ProductNumber = <span style="color: #a31515">&quot;AR-5381&quot;</span>;
product.MakeFlag = <span style="color: blue">false</span>;
product.FinishedGoodsFlag = <span style="color: blue">false</span>;
product.Color = <span style="color: blue">null</span>;
product.SafetyStockLevel = 1000;
product.ReorderPoint = 750;
product.StandardCost = 0.0000M;
product.ListPrice = 0.0000M;
product.Size = <span style="color: blue">null</span>;
product.SizeUnitMeasureCode = <span style="color: blue">null</span>;
product.WeightUnitMeasureCode = <span style="color: blue">null</span>;
product.Weight = <span style="color: blue">null</span>;
product.DaysToManufacture = 0;
product.ProductLine = <span style="color: blue">null</span>;
product.Class = <span style="color: blue">null</span>;
product.Style = <span style="color: blue">null</span>;
product.ProductSubcategoryID = <span style="color: blue">null</span>;
product.ProductModelID = <span style="color: blue">null</span>;
product.SellStartDate = <span style="color: #2b91af">DateTime</span>.Parse(<span style="color: #a31515">&quot;6/1/1998 12:00:00 AM&quot;</span>);
product.SellEndDate = <span style="color: blue">null</span>;
product.DiscontinuedDate = <span style="color: blue">null</span>;
product.Rowguid = <span style="color: blue">new </span><span style="color: #2b91af">Guid</span>(<span style="color: #a31515">&quot;694215b7-08f7-4c0d-acb1-d734ba44c0c8&quot;</span>);
product.ModifiedDate = <span style="color: #2b91af">DateTime</span>.Parse(<span style="color: #a31515">&quot;3/11/2004 10:01:36.827 AM&quot;</span>);

Products.Attach(product);

// Make the change here
product.Name = <span style="color: #a31515">&quot;Richard's product&quot;</span>;

SubmitChanges();</pre>
</blockquote>
<p>So you can avoid two trips to the database by doing the update manually and using the <strong>Attach </strong>method on the table you are updating.</p>
<p>Mind you, I&#8217;m not sure that&#8217;s worth it.</p>
<div style="float:right;margin:0 20px 20px 0">
<iframe style="width: 120px; height: 240px" marginwidth="0" marginheight="0" src="http://rcm.amazon.com/e/cm?t=netsmoo-20&amp;o=1&amp;p=8&amp;l=as1&amp;asins=1590597893&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;lc1=109DD0&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr" frameborder="0" scrolling="no"></iframe>
</div>
<p>If you want to know more about updating LINQ-to-SQL objects with the DataContext, I recommend <a href="http://www.amazon.com/gp/product/1590597893?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1590597893">Pro LINQ: Language Integrated Query in C# 2008</a><img style="margin: 0px; width: 1px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1590597893" width="1" border="0" />. It&#8217;s got 6 chapters just about LINQ-to-SQL, the DataContext, and concurrency issues.</p>
<p>P.S. In case you&#8217;re interested, I generated some of that code in LINQPad using the following code (it doesn&#8217;t work for dates or Guids, before anyone complains):</p>
<p><span style="color: blue">var </span>product = (<span style="color: blue">from </span>p <span style="color: blue">in</span>Products</p>
<p><span style="color: blue">where</span>p.ProductID == 1</p>
<p><span style="color: blue">select</span>p).Single();</p>
<p><span style="color: blue">var </span>fields = <span style="color: blue">from </span>field <span style="color: blue">in</span>product.GetType().GetFields()</p>
<p><span style="color: blue">select new</span>{</p>
<p>Name = field.Name,</p>
<p>Value = field.GetValue(product),</p>
<p>TypeName = field.FieldType.Name };</p>
<p><span style="color: blue">foreach </span>(<span style="color: blue">var </span>field <span style="color: blue">in</span>fields)</p>
<p><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">&quot;product.{0} = {1};&quot;</span>, field.Name,</p>
<p>field.TypeName == <span style="color: #a31515">&quot;String&quot;</span>? <span style="color: #a31515">&quot;\&quot;&quot;</span>+</p>
<p>field.Value + <span style="color: #a31515">&quot;\&quot;&quot;</span>:</p>
<p>field.Value ?? <span style="color: #a31515">&quot;null&quot;</span>);</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F18%2Fhow-to-update-data-with-linq-to-sql%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/18/how-to-update-data-with-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>How to See the SQL Generated by a LINQ to SQL Command</title>
		<link>http://www.richardbushnell.net/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/</link>
		<comments>http://www.richardbushnell.net/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/#comments</comments>
		<pubDate>Thu, 14 Feb 2008 09:11:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[LINQ to SQL]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/</guid>
		<description><![CDATA[Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader. If this is your code: using System; using System.Linq; using System.Data.Linq; namespace LINQtoSQLConsole { class Program { static void Main(string[] [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F14%2Fhow-to-see-the-sql-generated-by-a-linq-to-sql-command%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Quick tip: If you want to see the SQL generated by LINQ to SQL for a query or command, simply set the Log property of your generated DataContext class to an instance of a TextReader.</p>
<p>If this is your code:</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Linq;
<span style="color: blue">using </span>System.Data.Linq;

<span style="color: blue">namespace </span>LINQtoSQLConsole {
  <span style="color: blue">class </span><span style="color: #2b91af">Program </span>{
    <span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args) {

      <span style="color: blue">var </span>db = <span style="color: blue">new </span><span style="color: #2b91af">NorthwindDataContext</span>();

      <span style="color: green">// Use the console to see the SQL
      </span>db.Log = <span style="color: #2b91af">Console</span>.Out;

      <span style="color: green">// A query
      </span><span style="color: blue">var </span>cust = db.Customers.Single(
                    c =&gt; c.CustomerID == <span style="color: #a31515">"ALFKI"</span>);

      <span style="color: green">// An update
      </span>cust.Region = <span style="color: #a31515">"Northwest"</span>;
      db.SubmitChanges();
    }
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>&#8230; then this is what you&#8217;ll see:</p>
<p><a href="http://www.richardbushnell.net/wp-content/uploads/2008/02/image.png"><img border="0" width="244" src="http://www.richardbushnell.net/wp-content/uploads/2008/02/image-thumb.png" alt="image" height="134" style="border-width: 0px" /></a></p>
<p>Pretty good, eh?</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F14%2Fhow-to-see-the-sql-generated-by-a-linq-to-sql-command%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/14/how-to-see-the-sql-generated-by-a-linq-to-sql-command/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to Use Grouping in C# LINQ Syntax</title>
		<link>http://www.richardbushnell.net/2008/02/08/how-to-use-grouping-in-c-linq-syntax/</link>
		<comments>http://www.richardbushnell.net/2008/02/08/how-to-use-grouping-in-c-linq-syntax/#comments</comments>
		<pubDate>Fri, 08 Feb 2008 21:22:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[IGrouping]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/08/how-to-use-grouping-in-c-linq-syntax/</guid>
		<description><![CDATA[When you started using LINQ, did you think it looked like SQL? I did. The more I learned LINQ, the more I realized it wasn&#8217;t anything like SQL. Take grouping, for example. Because LINQ has a group by statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F08%2Fhow-to-use-grouping-in-c-linq-syntax%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>When you started using LINQ, did you think it looked like SQL? I did.</p>
<p>The more I learned LINQ, the more I realized it <em>wasn&#8217;t anything like</em> SQL. Take grouping, for example. Because LINQ has a <span style="color: blue">group by </span>statement, and it looks like SQL, I assumed that the syntax for grouping in LINQ would be just like SQL. Ha ha! Wrong! As soon as I tried to use it, I discovered that the LINQ syntax is not only nothing like the SQL equivalent, but the whole grouping concept in LINQ is completely different too.</p>
<p>At first glance, the two syntaxes look <em>slightly </em>similar.</p>
<p>SQL:</p>
<pre class="code"><span style="color: blue">select </span>ReportsTo<span style="color: gray">, </span><span style="color: magenta">count</span><span style="color: gray">(</span>LastName<span style="color: gray">) </span><span style="color: blue">as </span>NameCount
<span style="color: blue">from </span>Employees
<span style="color: blue">group by </span>ReportsTo</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>LINQ (C#):</p>
<pre class="code"><span style="color: blue">from </span>employee <span style="color: blue">in </span>Employees
<span style="color: blue">group </span>employee <span style="color: blue">by </span>employee.ReportsTo</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Ignoring the omission of the select statement from LINQ, and the requirement of a range variable, they do look similar. But looks can be deceiving.</p>
<p>Let me explain why.</p>
<p><span id="more-48"></span></p>
<h2>Grouping in SQL</h2>
<p>In SQL, you typically group a set of entities using the following syntax:</p>
<pre class="code"><span style="color: blue">select </span>ReportsTo<span style="color: gray">, </span><span style="color: magenta">count</span><span style="color: gray">(</span>LastName<span style="color: gray">) </span><span style="color: blue">as </span>NameCount
<span style="color: blue">from </span>Employees
<span style="color: blue">group by </span>ReportsTo</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This kind of query results in a simple table with two columns: ReportsTo and NameCount. The count of the names was grouped into a single column using an aggregate function.</p>
<p>Of course, this is a simple example; you could do much more complex grouping by using more expressions in the aggregation or the group by statement. Whatever the grouping though, the result is a flat table.</p>
<p>LINQ is different. Completely different.</p>
<h2>Grouping in LINQ</h2>
<p>Before you can understand the LINQ syntax, you have to understand how grouping works in LINQ.</p>
<p>When you use the <span style="color: blue">group by </span>statement, the C# compiler translates it to the LINQ Enumerable&#8217;s GroupBy extension method. The GroupBy method returns an object of type</p>
<pre class="code"><span style="color: #2b91af">  IEnumerable</span>&lt;<span style="color: #2b91af">IGrouping</span>&lt;TKey, TSource&gt;&gt;</pre>
<p>The GroupBy method takes a parameter of a delegate which specifies the key of each grouping. The key is defined to be of type TKey, and is usually inferred by the compiler depending on the expression.</p>
<p>The key to understanding the C# query syntax is that you <em>don&#8217;t</em> get back a <em>flat</em> structure from <span style="color: blue">group by</span>, as you would with SQL. You actually get an &#8220;IEnumerable&#8221; of &#8220;IGrouping&#8221; objects.</p>
<p>The IGrouping interface has only one property, &#8220;Key&#8221;, and implements IEnumerable&lt;TElement&gt;. Again, TElement is usually inferred. &#8220;Key&#8221; is typed as the generic type you define for TKey. For the minute, that&#8217;s not so important, so we&#8217;ll come back to the Key later.</p>
<p>One of the first indications that LINQ is different to SQL is that you discover it is possible to finish a LINQ statement with a <span style="color: blue">group by </span>statement without needing a Select. As IGrouping implements IEnumerable, <span style="color: blue">group by </span>actually returns an IEnumerable of IEnumerable. The result is a set of sets. It&#8217;s <em>not</em> a flat table. To use it, you have to iterate over it again or perform another operation on the set.</p>
<p>Let&#8217;s see if an example can make it clearer.</p>
<p>When grouping a set of employees, you might use the following code:</p>
<pre class="code"><span style="color: blue">var </span>emp1 = <span style="color: blue">new </span>{ ReportsTo = 1, LastName = <span style="color: #a31515">"Richard" </span>};
<span style="color: blue">var </span>emp2 = <span style="color: blue">new </span>{ ReportsTo = 1, LastName = <span style="color: #a31515">"Christopher" </span>};
<span style="color: blue">var </span>emp3 = <span style="color: blue">new </span>{ ReportsTo = 2, LastName = <span style="color: #a31515">"John" </span>};
<span style="color: blue">var </span>emp4 = <span style="color: blue">new </span>{ ReportsTo = 2, LastName = <span style="color: #a31515">"Greg" </span>};
<span style="color: blue">var </span>employees = <span style="color: blue">new</span>[] { emp1, emp2, emp3, emp4 };

<span style="color: blue">var </span>groups =
<span style="color: blue">  from </span>employee <span style="color: blue">in </span>employees
<span style="color: blue">  group </span>employee <span style="color: blue">by </span>employee.ReportsTo;

<span style="color: blue">foreach </span>(<span style="color: blue">var </span>group <span style="color: blue">in </span>groups)
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"{0} employees report to {1}."</span>,
    group.Key, group.Count());</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>(Don&#8217;t worry about the anonymous class definitions for now. You just have to know that my employee objects are all treated as the same type internally, so this is valid C# code.)</p>
<p>The employees variable is of type IEnumerable, so it can be used in a LINQ statement. The groups variable is also an IEnumerable, as it is a set of results, as usually returned by a LINQ statement. Remember though, <em>it&#8217;s not like </em>the set you would get back in a SQL statement. It is actually an IEnumerable of IGrouping, or an IEnumerable of IEnumerable.</p>
<p>To do something with the grouping, you have to either treat it as another IEnumerable, and iterate over it, or use methods like Count() to do something with it.</p>
<pre class="code"><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: blue">var <span style="color: black">group </span>in </span><span style="color: black">groups)
  </span><span style="color: blue">foreach </span><span style="color: black">(</span><span style="color: blue">var </span><span style="color: black">employee </span><span style="color: blue">in <span style="color: black">group</span></span><span style="color: black">)
    Console.WriteLine(</span><span style="color: #dc1414">"{0} reports to {1}"</span><span style="color: black">,
      employee.LastName, employee.ReportsTo);</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This is how LINQPad shows what is contained in the groups variable:</p>
<table class="MsoNormalTable" style="border: medium none ; margin-left: 1.2pt; border-collapse: collapse" border="1" cellpadding="0" cellspacing="0">
<tr>
<td style="border: 1pt solid #aaaaaa; padding: 0cm 2.4pt 1.2pt 1.2pt; background: #1177bb none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; color: white; font-family: 'Tahoma','sans-serif'"><span><u><span>IEnumerable&lt;IGrouping&lt;Int32,&gt;&gt;</span></u></span> </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<table class="MsoNormalTable" style="border-collapse: collapse" border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><em><span style="font-size: 9.5pt; color: green; font-family: 'Verdana','sans-serif'">Key=</span></em><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'"> </span></p>
</td>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">1 </span></p>
</td>
</tr>
</table>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal">&nbsp;</p>
<table class="MsoNormalTable" style="border: medium none ; margin-left: 1.2pt; border-collapse: collapse" border="1" cellpadding="0" cellspacing="0">
<tr>
<td style="border: 1pt solid #aaaaaa; padding: 0cm 2.4pt 1.2pt 1.2pt; background: #1177bb none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" colspan="2" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; color: white; font-family: 'Tahoma','sans-serif'"><span><u><span>IGrouping&lt;Int32,&gt; (2 items)</span></u></span> </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">ReportsTo </span></strong></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">LastName </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">1 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">Richard </span></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">1 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">Christopher </span></p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<table class="MsoNormalTable" style="border-collapse: collapse" border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><em><span style="font-size: 9.5pt; color: green; font-family: 'Verdana','sans-serif'">Key=</span></em><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'"> </span></p>
</td>
<td style="padding: 0cm 1.2pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">2 </span></p>
</td>
</tr>
</table>
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="display: none; font-size: 9.5pt; font-family: 'Verdana','sans-serif'"></span></p>
<table class="MsoNormalTable" style="border: medium none ; margin-left: 1.2pt; border-collapse: collapse" border="1" cellpadding="0" cellspacing="0">
<tr>
<td style="border: 1pt solid #aaaaaa; padding: 0cm 2.4pt 1.2pt 1.2pt; background: #1177bb none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" colspan="2" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; color: white; font-family: 'Tahoma','sans-serif'"><span><u><span>IGrouping&lt;Int32,&gt; (2 items)</span></u></span> </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">ReportsTo </span></strong></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(119, 119, 119) rgb(119, 119, 119) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt; background: #dddddd none repeat scroll 0% 50%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><strong><span style="font-size: 8.5pt; font-family: 'Tahoma','sans-serif'">LastName </span></strong></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">2 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">John </span></p>
</td>
</tr>
<tr>
<td style="border-style: none solid solid; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170); border-width: medium 1pt 1pt; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">2 </span></p>
</td>
<td style="border-style: none solid solid none; border-color: -moz-use-text-color rgb(170, 170, 170) rgb(170, 170, 170) -moz-use-text-color; border-width: medium 1pt 1pt medium; padding: 1.2pt 2.4pt" valign="top">
<p class="MsoNormal" style="margin-bottom: 0pt; line-height: normal"><span style="font-size: 9.5pt; font-family: 'Verdana','sans-serif'">Greg </span></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
<p>Notice that each IGrouping has an associated Key property of type Int32.</p>
<h2>Grouping Syntax in LINQ</h2>
<p class="MsoNormal">So now it should be a little easier to understand how to use the LINQ <span style="color: blue">group by</span> statement.</p>
<p class="MsoNormal">In LINQ, you always need to <strong>declare the range variable </strong>between <span style="color: blue">group</span> and <span style="color: blue">by</span>.</p>
<p class="MsoNormal"><font size="2"><font face="Courier New"><span style="color: blue">from </span>employee <span style="color: blue">in </span>Employees </font></font></p>
<p><span style="color: blue"><font size="2"><font face="Courier New">group </font></font></span><font size="2"><font face="Courier New">employee <span style="color: blue">by </span>employee.ReportsTo</font></font></p>
<p class="MsoNormal">After <span style="color: blue">by</span>, you give an expression which returns the value for the <span style="color: blue">Key</span>. The enumeration is then split into groups of <span style="color: blue">IGroupings </span>where the key for each item in that <span style="color: blue">IGrouping</span> is the same.</p>
<p class="MsoNormal">So here, we specify the employee.ReportsTo variable as the key. Each employee with a different value for ReportsTo creates a new <span style="color: blue">IGrouping</span> with a <span style="color: blue">Key</span> of that value. The employee is then added to that new <span style="color: blue">IGrouping</span> as an item. The <span style="color: blue">IGrouping</span> is then added to the returned <span style="color: blue">IEnumerable&lt;<span style="color: blue">IGrouping&lt;&gt;<strong>&gt;</strong></span></span>.</p>
<p class="MsoNormal">The next time an item in the employees variable has the same value for ReportsTo as the <span style="color: blue">Key</span> property of an already-existing <span style="color: blue">IGrouping</span> object, the item is simply added to that <span style="color: blue">IGrouping</span>.</p>
<p class="MsoNormal">Of course, that&#8217;s probably not the way it works under the covers. But I&#8217;m not trying to specify the algorithm, just what happens in the end result.</p>
<p class="MsoNormal">In the end, an object implementing <span style="color: blue">IEnumerable&lt;<span style="color: blue">IGrouping&lt;&gt;<strong>&gt;</strong></span></span> is returned by the LINQ statement. As each item in the <span style="color: blue">IEnumerable </span>is an <span style="color: blue"><span style="color: blue">IGrouping</span></span>, you can either use it&#8217;s <span style="color: blue">Key</span> or treat it as an <span style="color: blue">IEnumerable</span>.</p>
<p class="MsoNormal">So there you have it. Just remember, group by is nothing like SQL, and it returns an <span style="color: blue">IEnumerable </span>of <span style="color: blue">IGrouping</span>, and you should stay happy.</p>
<p class="MsoNormal">At least until you meet SelectMany&#8230; :=)</p>
<div style="float:left;margin:0 20px 20px 0">
<iframe src="http://rcm.amazon.com/e/cm?t=netsmoo-20&amp;o=1&amp;p=8&amp;l=as1&amp;asins=0596527578&amp;fc1=000000&amp;IS2=1&amp;lt1=_blank&amp;lc1=2586B3&amp;bc1=000000&amp;bg1=FFFFFF&amp;f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<p>If you want to learn more about grouping in LINQ, take a look at chapter 9 of the excellent <a href="http://www.amazon.com/gp/product/0596527578?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0596527578">C# 3.0 in a Nutshell: A Desktop Quick Reference (In a Nutshell (O&#8217;Reilly))</a><img src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=0596527578" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />, by Ben and Joseph Albahari. The chapter has some great explanations and examples. In particular, they have an example of grouping with multiple keys, which I found very interesting.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F08%2Fhow-to-use-grouping-in-c-linq-syntax%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/08/how-to-use-grouping-in-c-linq-syntax/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>LINQ to DataSets &#8211; the Missing Manual</title>
		<link>http://www.richardbushnell.net/2008/02/04/linq-to-datasets-the-missing-manual/</link>
		<comments>http://www.richardbushnell.net/2008/02/04/linq-to-datasets-the-missing-manual/#comments</comments>
		<pubDate>Mon, 04 Feb 2008 09:50:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[free]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/02/04/linq-to-datasets-the-missing-manual/</guid>
		<description><![CDATA[Last week I had to prepare a small presentation for a new LINQ workshop. For my research, I browsed through the MSDN documentation on LINQ where I came across a reference to &#34;LINQ to DataSets&#34;. I couldn&#8217;t find any more information about it though, and so LINQ to DataSets got a small mention in my [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F04%2Flinq-to-datasets-the-missing-manual%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p><a href="http://www.amazon.com/gp/product/1933988169?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1933988169"><img style="margin: 0px 20px 20px 0px" src="/images/21bKr5u-oYL._AA_SL160_.jpg" align="left" border="0" /></a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1933988169" width="1" border="0" /></p>
<p>Last week I had to prepare a small presentation for a new LINQ workshop. For my research, I browsed through the MSDN documentation on LINQ where I came across a reference to &quot;LINQ to DataSets&quot;. I couldn&#8217;t find any more information about it though, and so LINQ to DataSets got a small mention in my presentation, but I couldn&#8217;t say anything more about it.</p>
<p>This morning I discovered that <a href="http://weblogs.asp.net/fmarguerie/archive/2008/01/21/linq-in-action-final-pdf-ebook-available.aspx" target="_blank">Fabrice Marguerie</a> and his co-authors have published a bonus <a href="http://www.manning-source.com/books/marguerie/bonusch14.pdf" target="_blank">47-page chapter</a> of their book &quot;<a href="http://www.amazon.com/gp/product/1933988169?ie=UTF8&amp;tag=netsmoo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=1933988169">LINQ in Action</a><img style="margin: 0px; border-top-style: none! important; border-right-style: none! important; border-left-style: none! important; border-bottom-style: none! important" height="1" alt="" src="http://www.assoc-amazon.com/e/ir?t=netsmoo-20&amp;l=as2&amp;o=1&amp;a=1933988169" width="1" border="0" />&quot;, all about this very subject. The chapter is called &quot;Working with LINQ and DataSets&quot;, and they have made a <a href="http://www.manning-source.com/books/marguerie/bonusch14.pdf" target="_blank">PDF version available online</a> for FREE download from the <a href="http://www.manning.com/marguerie/" target="_blank">Manning Press website</a>.</p>
<p>You can <a href="http://www.manning-source.com/books/marguerie/bonusch14.pdf" target="_blank">go get it</a> right now.</p>
<p>Thanks Fabrice, for filling in the missing gap.</p>
<p>I&#8217;m going back to update my presentation&#8230;</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F02%2F04%2Flinq-to-datasets-the-missing-manual%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/02/04/linq-to-datasets-the-missing-manual/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using LinqPad to Create a Time-Selector Drop-Down List</title>
		<link>http://www.richardbushnell.net/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/</link>
		<comments>http://www.richardbushnell.net/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/#comments</comments>
		<pubDate>Fri, 18 Jan 2008 17:47:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[LinqPad]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/</guid>
		<description><![CDATA[I am really getting into LINQ now! I think it&#8217;s fantastic. I recently wanted to develop a quick drop-down list in ASP.Net which allows a user to select a time of day from a list. The times are 15 minutes apart, so the list would look like this: &#8230; 08:00 08:15 08:30 08:45 09:00 &#8230; [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F18%2Fusing-linqpad-to-create-a-time-selector-drop-down-list%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>I am <em>really </em>getting into LINQ now! I think it&#8217;s fantastic. I recently wanted to develop a quick drop-down list in ASP.Net which allows a user to select a time of day from a list. The times are 15 minutes apart, so the list would look like this:</p>
<p>&#8230;<br /> 08:00<br /> 08:15<br /> 08:30<br /> 08:45<br /> 09:00<br /> &#8230;</p>
<p>&#8230; and so on.</p>
<p>Before LINQ, I would have done this with a for loop, like this:</p>
<pre class="code"><span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt; times = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: blue">string</span>&gt;();
<span style="color: blue">for </span>(<span style="color: blue">int </span>hour = 0; hour &lt; 24; hour++)
  <span style="color: blue">for </span>(<span style="color: blue">int </span>minute = 0; minute &lt; 60; minute++)
    <span style="color: blue">if </span>(minute % 15 == 0)
       times.Add(<span style="color: blue">string</span>.Format(
         <span style="color: #a31515">"{0:00}:{1:00}"</span>, hour, minute));</pre>
<p>That&#8217;s not difficult, although it&#8217;s not so easy to understand. I would have to write a small console app or test to make sure I had done it correct though.</p>
<p>I thought this might be a good opportunity to use <a href="http://www.linqpad.net" target="_blank">LinqPad</a>. It&#8217;s a great tool. You can use it to test a LINQ statement in a live window, so I thought I&#8217;d give it a go.</p>
<p>First I needed a LINQ statement to test.</p>
<p><span id="more-36"></span></p>
<h2>Designing the LINQ Statement</h2>
<p>The first thing I needed was an integer for the hour. That&#8217;s quite easy, especially if you use the Range Extension Method technique as I wrote about before. That method allows you to create an IEnumerable&lt;int&gt; from a simple statement, like 1.To(10). So to get the hours of the day, I can simply start with:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now I need to do a cross-join with the minutes. In C# comprehension syntax, you do that by simply adding another <font color="#0000ff">from</font> statement. At first, I thought I could do it by using an enumeration of minutes, specifying each value I wanted specifically. To do that I wrote this:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)
</span><span style="color: blue">from </span><span style="color: black">minute </span><span style="color: blue">in new</span><span style="color: black">[] {</span><span style="color: #c81efa">0</span><span style="color: black">, </span><span style="color: #c81efa">15</span><span style="color: black">, </span><span style="color: #c81efa">30</span><span style="color: black">, </span><span style="color: #c81efa">45</span><span style="color: black">}</span></pre>
<p><a href="http://11011.net/software/vspaste"></a>That works very nicely. I think it&#8217;s easy to understand too. Even if you were going to come back to it years from now, you could still easily see what is being done.</p>
<p>Another alternative is to do the same as the <font color="#0000ff">for</font> statement above, go through the numbers 0 to 59, selecting only those which are divisible by 15. You would do that using another range and a filter:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)
</span><span style="color: blue">from </span><span style="color: black">minute </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">59</span><span style="color: black">)
</span><span style="color: blue">where </span><span style="color: black">minute % </span><span style="color: #c81efa">15 </span><span style="color: black">== </span><span style="color: #c81efa">0</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Again, I like the way this looks. Another developer should have no difficulty reading that.</p>
<p>To select the string, we will also use the same format as before, this time using the <font color="#0000ff">select</font> keyword:</p>
<pre class="code"><span style="color: blue">select string</span><span style="color: black">.Format(</span><span style="color: #dc1414">"{0:00}:{1:00}"</span><span style="color: black">, hour, minute)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You then simply assign the value of this statement to a variable, like this:</p>
<pre class="code"><span style="color: blue">var </span>times = <span style="color: blue">from </span>hour <span style="color: blue">in </span>0.To(23)
            <span style="color: blue">from </span>minute <span style="color: blue">in </span>0.To(59)
            <span style="color: blue">where </span>minute % 15 == 0
            <span style="color: blue">select string</span>.Format(<span style="color: #a31515">"{0:00}:{1:00}"</span>, hour, minute);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h2>Using LinqPad to Test the Result</h2>
<p>Now, if you haven&#8217;t already, go <a href="http://www.linqpad.net/" target="_blank">download LinqPad from here</a>, and open it up. You will see a window to write a statement in the top right.</p>
<p>Before you continue, you need to add the extension methods to use my &#8220;To()&#8221; method. As a treat, just for you, <a href="http://www.richardbushnell.net/wp-content/uploads/2008/01/richardbushnellextensions.zip" target="_blank">here&#8217;s a simple assembly and a code file</a> you can use straight away. Download it, save the binary dll somewhere, then do the following in LinqPad:</p>
<ol>
<li>From the menu, click &#8220;Query&#8221;, then &#8220;Advanced Properties&#8221; (or press F4).
<li>On the Additional References tab, click the &#8220;Add&#8230;&#8221; button.
<li>Click the &#8220;Browse&#8230;&#8221; button on the window which pops up.
<li>Go to the location you saved RichardBushnell.Extensions.dll to, and select it. You should see it added to the list of additional references.
<li>Change to the Additional Namespace Imports tab.
<li>Type &#8220;RichardBushnell.Extensions&#8221;
<li>Click &#8220;OK&#8221;. </li>
</ol>
<p>Now, put your cursor in the Query1 tab, and paste in the following:</p>
<pre class="code"><span style="color: blue">from </span><span style="color: black">hour </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">23</span><span style="color: black">)
</span><span style="color: blue">from </span><span style="color: black">minute </span><span style="color: blue">in </span><span style="color: #c81efa">0</span><span style="color: black">.To(</span><span style="color: #c81efa">59</span><span style="color: black">)
</span><span style="color: blue">where </span><span style="color: black">minute % </span><span style="color: #c81efa">15 </span><span style="color: black">== </span><span style="color: #c81efa">0
</span><span style="color: blue">select string</span><span style="color: black">.Format(</span><span style="color: #dc1414">"{0:00}:{1:00}"</span><span style="color: black">, hour, minute)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Press F5, and you will see a generated list like this:</p>
<p><a href="http://www.richardbushnell.net/wp-content/uploads/2008/01/image2.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="176" alt="image" src="http://www.richardbushnell.net/wp-content/uploads/2008/01/image-thumb2.png" width="244" border="0"></a></p>
<p>And that&#8217;s it! You can now see <em>exactly</em> what you will get when you run this code.</p>
<p>What do you think? I&#8217;d love to hear your comments.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F18%2Fusing-linqpad-to-create-a-time-selector-drop-down-list%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/01/18/using-linqpad-to-create-a-time-selector-drop-down-list/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

