<?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>i-think Twenty-Two &#187; LINQ</title>
	<atom:link href="http://www.i-think22.net/archives/category/i-think/i-think_it/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.i-think22.net</link>
	<description>Now with more rambling</description>
	<lastBuildDate>Fri, 12 Feb 2010 04:01:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>LINQ to SQL and tables with no Primary Key</title>
		<link>http://www.i-think22.net/archives/2009/07/24/linq-to-sql-and-tables-with-no-primary-key/</link>
		<comments>http://www.i-think22.net/archives/2009/07/24/linq-to-sql-and-tables-with-no-primary-key/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 20:24:39 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/07/24/linq-to-sql-and-tables-with-no-primary-key/</guid>
		<description><![CDATA[I ran into an interesting issue with LINQ to SQL yesterday. I had to update a table with no Primary Key. As I expected, LINQ to SQL wasnâ€™t too happy with this scenario. Unfortunately LINQ to SQL will only throw an exception when you try to Insert or Delete a record with no primary key. [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into an interesting issue with LINQ to SQL yesterday. I had to update a table with no Primary Key. As I expected, LINQ to SQL wasnâ€™t too happy with this scenario. Unfortunately LINQ to SQL will only throw an exception when you try to Insert or Delete a record with no primary key. Updates fail silently.</p>
<p>Itâ€™s actually quite obvious when you look into what is happening. To do an update you would usually do something like this:</p>
<pre class="prettyprint">var update = (from v in db.SimpleRecords
              where v.identifier == 12
              select v).First();
update.value = &quot;new value&quot;;
db.SubmitChanges();</pre>
<p>Of course, nothing happens. Hereâ€™s the code (slightly edited for readability) that is generated by the LINQ to SQL classes:</p>
<pre class="prettyprint">[Table(Name=&quot;dbo.SimpleRecord&quot;)]
public partial class SimpleRecord
{
   private int _identifier;

   private string _value;

      public SimpleTable()
      {
      }

      [Column(Storage=&quot;_identifier&quot;, AutoSync=AutoSync.Always,
         DbType=&quot;Int NOT NULL IDENTITY&quot;, IsDbGenerated=true)]
      public int identifier
      {
         get
         {
            return this._identifier;
         }
         set
         {
            if (this._identifier != value)
            {
               this._identifier = value;
            }
         }
      }

      [Column(Storage=&quot;_value&quot;, DbType=&quot;VarChar(50)&quot;)]
      public string value
      {
         get
         {
            return this._value;
         }
         set
         {
            if (this._value != value)
            {
               this._value = value;
            }
         }
      }
}</pre>
<p>Without a primary key the two following interfaces arenâ€™t emitted: <code class="prettyprint">INotifyPropertyChanging</code> and <code class="prettyprint">INotifyPropertyChanged</code></p>
<p>Therefore LINQ to SQL doesnâ€™t know that your record has changed (so canâ€™t warn you that it canâ€™t update).</p>
<p>Now that you understand the problem the solution is simple: Define a primary key in your table.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/07/24/linq-to-sql-and-tables-with-no-primary-key/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>LINQ Talk from Queensland MSDN User Group</title>
		<link>http://www.i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group/</link>
		<comments>http://www.i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group/#comments</comments>
		<pubDate>Wed, 06 May 2009 20:23:52 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/?p=261</guid>
		<description><![CDATA[Last month I did a talk on LINQ at the Queensland MSDN User Group. For your viewing pleasure the talk is available on Live Meeting. Check it out here: LINQ: Powerful Stuff (QMSDNUG) You may need to skip the first 5 minutes. Slides are available here: http://linq.i-think22.net/LinqApril2009.pdf Demos will be available soon.]]></description>
			<content:encoded><![CDATA[<p>Last month I did a talk on LINQ at the Queensland MSDN User Group. For your viewing pleasure the talk is available on Live Meeting. Check it out here:</p>
<p><a href="https://www112.livemeeting.com/cc/microsoft/view?cn=&#038;id=59CJFS&#038;pw=">LINQ: Powerful Stuff (QMSDNUG)</a></p>
<p>You may need to skip the first 5 minutes.</p>
<p>Slides are available here: <a href="http://linq.i-think22.net/LinqApril2009.pdf">http://linq.i-think22.net/LinqApril2009.pdf</a></p>
<p>Demos will be available soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/05/07/linq-talk-from-queensland-msdn-user-group/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing XML with XElement</title>
		<link>http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/</link>
		<comments>http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 22:39:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/</guid>
		<description><![CDATA[In my last post we looked at how you can use LINQ to XML and XElement to parse XML. But what if you want to create XML files programmatically? Or modify an existing XML document? Let&#8217;s start by looking at how we might add a new entry to our blog. Here is the XML file [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post we looked at <a href="http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/">how you can use LINQ to XML and XElement to parse XML</a>. But what if you want to create XML files programmatically? Or modify an existing XML document?</p>
<p>Let&#8217;s start by looking at how we might add a new entry to our blog. Here is the XML file again:</p>
<pre class="prettyprint">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;Blog&gt;
   &lt;Entries&gt;
      &lt;Entry Archived="false"&gt;
         &lt;Title&gt;My First Post&lt;/Title&gt;
         &lt;Body&gt;I love LINQ. It's the best&lt;/Body&gt;
         &lt;Comments&gt;
            &lt;!-- TODO: Shouldn't comments have authors? --&gt;
            &lt;Comment&gt;I love LINQ more&lt;/Comment&gt;
            &lt;Comment&gt;LINQ is the way of the future.&lt;/Comment&gt;
         &lt;/Comments&gt;
      &lt;/Entry&gt;
   &lt;/Entries&gt;
&lt;/Blog&gt;</pre>
<p>So we want to add a new Entry under the Entries element. We&#8217;ll also assume that our XML file has been parsed into an <code class="prettyprint">XElement</code> variable <code class="prettyprint">blog</code>.</p>
<p>We&#8217;ll start by creating our entry first:</p>
<pre class="prettyprint">var entry = new XElement("Entry");
entry.SetAttributeValue("Archived", false);
entry.Add(new XElement("Title", "My Second Post"));
entry.Add(new XElement("Body", "Just a quick post."));
entry.Add(new XElement("Comments"));</pre>
<p>We started by creating the element, set the &#8220;Archived&#8221; attribute, then added the other necessary elements. I&#8217;ve still added the Comments element even though it will be empty. Depending on the rules that have been set about how I should layout the XML it might be optional.</p>
<p>To check that my code worked I plugged it into <a href="http://www.linqpad.net/">LINQPad</a> and dumped the value of entry like so:</p>
<pre class="prettyprint">entry.ToString().Dump();</pre>
<p>The results showed me the following:</p>
<pre class="prettyprint">&lt;Entry Archived="false"&gt;
   &lt;Title&gt;My Second Post&lt;/Title&gt;
   &lt;Body&gt;Just a quick post.&lt;/Body&gt;
   &lt;Comments /&gt;
&lt;/Entry&gt;
</pre>
<p>Wow, that&#8217;s exactly what we want. Even though we used a <code class="prettyprint">Boolean</code> value instead of a <code class="prettyprint">String</code> for the attribute, <code class="prettyprint">XElement</code> was smart enough to display its value as a human readable string. The XML is also nicely formatted and readable. I added the call to <code class="prettyprint">ToString()</code> to emphasise that it wasn&#8217;t LINQPad that was responsible for the improved formatting.</p>
<p>What we have done here is generate an XML fragment. Sometimes it is easier to think of large XML files as smaller fragments that can be handled independently.</p>
<p>So now all we have to do is find the Entries element and add our <code class="prettyprint">entry</code> <code class="prettyprint">XElement</code> to it like so.</p>
<pre class="prettyprint">blog.Element("Entries").Add(entry);</pre>
<p>This will leave us with the final XML looking like this:</p>
<pre class="prettyprint">&lt;Blog&gt;
   &lt;Entries&gt;
     &lt;Entry Archived="false"&gt;
       &lt;Title&gt;My First Post&lt;/Title&gt;
       &lt;Body&gt;I love LINQ. It's the best&lt;/Body&gt;
       &lt;Comments&gt;
         &lt;!-- TODO: Shouldn't comments have authors? --&gt;
         &lt;Comment&gt;I love LINQ more&lt;/Comment&gt;
         &lt;Comment&gt;LINQ is the way of the future.&lt;/Comment&gt;
       &lt;/Comments&gt;
     &lt;/Entry&gt;
     &lt;Entry Archived="false"&gt;
       &lt;Title&gt;My Second Post&lt;/Title&gt;
       &lt;Body&gt;Just a quick post.&lt;/Body&gt;
       &lt;Comments /&gt;
     &lt;/Entry&gt;
   &lt;/Entries&gt;
&lt;/Blog&gt;</pre>
<h3>What about our XML declaration?</h3>
<p>You might be wondering why the <code class="prettyprint">ToString()</code> method of <code class="prettyprint">XElement</code> doesn&#8217;t include the XML declaration. Because XElement represents a fragment of XML which could appear anywhere in an XML document. If it included the XML declaration it would lose this flexibility. However there is a workaround if you are outputting to a final file.</p>
<pre class="prettyprint">var blogDump = new StringBuilder();
blog.Save(new StringWriter(blogDump));</pre>
</p>
<p>The <code class="prettyprint">Save()</code> method on <code class="prettyprint">XElement</code> automatically adds an appropriate XML declaration, which is probably a good idea as it sorts out the complicated things like the encoding and XML version (which I&#8217;ve never seen as anything other than 1.0 to date). The <code class="prettyprint">Save()</code> method can take either the name of a file (as a <code class="prettyprint">String</code>), an <code class="prettyprint">XmlWriter</code> or <code class="prettyprint">TextWriter</code>. In the example above I&#8217;ve used a <code class="prettyprint">StringWriter</code> (which is a subclass of <code class="prettyprint">TextWriter</code>) to save XML to a <code class="prettyprint">StringBuilder</code> object which I could then use to build a string containing the XML. <code class="prettyprint">Save()</code> also takes a second parameter, <code class="prettyprint">SaveOptions</code> which allows you to save your XML file without the extra whitespace that I&#8217;ve shown above. If you want to save those bytes it might be worth looking at this option.</p>
<h3>Where do we go from here?</h3>
<p>I haven&#8217;t yet decided what my next LINQ post will cover (although LINQ to Entities is high on the agenda), so I won&#8217;t promise anything here now. I have much more to say still about LINQ, so feel free to post in the comments suggestions for areas to cover in future posts and the areas you would like to see covered in more detail. So far this has been fairly introductory and we&#8217;ll be building towards more advanced topics over the coming weeks.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/27/writing-xml-with-xelement/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XML Made Easy with LINQ to XML</title>
		<link>http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/</link>
		<comments>http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 22:58:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/</guid>
		<description><![CDATA[XML is a fantastic way to structure information. Here are the two things I like most about XML. It&#8217;s fundamental concepts are simple, making many XML files readable by regular humans. The formalised structure enables re-use of a more generalised XML parser. Projects can certainly suffer from too much XML or XML is used when [...]]]></description>
			<content:encoded><![CDATA[<p>XML is a fantastic way to structure information. Here are the two things I like most about XML.</p>
<ol>
<li>It&#8217;s fundamental concepts are simple, making many XML files readable by regular humans.  </li>
<li>The formalised structure enables re-use of a more generalised XML parser.</li>
</ol>
<p>Projects can certainly suffer from too much XML or XML is used when a better option exists. Once your XML files become too difficult to read in a text editor it may be better to look at another option (or better design your XML schema).</p>
<h3>A lightning fast introduction to XML</h3>
<p>Skip this section if you already know XML, but take time to look at this XML sample as it will be used throughout the article.</p>
<pre class="prettyprint">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;Blog&gt;
   &lt;Entries&gt;
      &lt;Entry Archived="false"&gt;
         &lt;Title&gt;My First Post&lt;/Title&gt;
         &lt;Body&gt;I love LINQ. It's the best&lt;/Body&gt;
         &lt;Comments&gt;
            &lt;!-- TODO: Shouldn't comments have authors? --&gt;
            &lt;Comment&gt;I love LINQ more&lt;/Comment&gt;
            &lt;Comment&gt;LINQ is the way of the future.&lt;/Comment&gt;
         &lt;/Comments&gt;
      &lt;/Entry&gt;
   &lt;/Entries&gt;
&lt;/Blog&gt;</pre>
<p>Above is an example of a simple XML file. XML files follow a structured pattern called a <strong>schema</strong>. The schema defines the rules for what is allowed where and generally defines the structure of your file. Fortunately you don&#8217;t need to write a formal schema to get started with XML. Instead you can just start laying out your data. That&#8217;s where the &#8220;X&#8221; in XML comes from, because it is <strong>eXtensible</strong>.</p>
<p>So the sample XML above is being used to store the contents of a simple blog. XML isn&#8217;t the best way to do this, but a blog is a simple well understood concept. If you read my article on <a href="http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/">LINQ to SQL</a> you might notice that this is very similar to the database example I used there.</p>
<p>Every XML document <em>should</em> start with what is known as an <strong>XML declaration</strong>. It&#8217;s in the first line of the XML and defines the version of the XML as well as the encoding of the file. If you are using notepad you can select the encoding when you save the file. The topic of encodings is out of the scope of this article.</p>
<p>The next important element that all XML files need is a <strong>root node</strong>. In this example our root node is called &#8220;Blog&#8221; and it holds all of our other elements. There can only be one root node in an XML document so if we wanted another blog we would have to put it in another XML file or redesign our XML to have a new root node (such as BlogCollection).</p>
<p>From there we can see that our XML document is made up of two key parts, elements and attributes. <strong>Elements</strong> are the things in angle brackets (called <strong>tags</strong>) and an element continues until it is closed with a matching closing tag. <strong>Closing tags</strong> are different from regular tags as they have a forward slash (/) before the name of the tag. We will use the term element to describe everything from the opening tag (a regular tag) to the closing tag, and a tag as the bit with the angle brackets.</p>
<p>There is also a special kind of tag called a <strong>self-closing tag</strong> that is both an opening tag and a closing tag. These tags have a forward slash before the closing angle bracket. For example:</p>
<pre class="prettyprint">&lt;SelfClosingTag /&gt;</pre>
</p>
<p>The space before the forward slash is optional (and stems back to compatibility with HTML). Personally I like keeping the space there, but your project may have different rules.</p>
<p>The other important concept is attributes. <strong>Attributes</strong> go inside the tag to provide more information about a tag. Attributes can only be used once per element (but one element can have multiple attributes). In the example above, we have given the entry tag the Archived attribute.</p>
<p>Sometimes it can be difficult to determine whether data should be expressed as an attribute or as a <strong>child element</strong> (an element inside another element). Typically the rule of thumb is that an attribute should be describing metadata, that is extra information about the element itself and how it might be interpreted. Occasionally this doesn&#8217;t clear things up at all. If you are still confused, consider the complexity of the data and whether multiple instances of the data will be required. Complex and repeating data is a sure sign that you want to use an element.</p>
<p>Importantly elements can contain other elements which can in turn contain more elements (and so on). XML follows a very strict hierarchy (which makes it easy to navigate) so an element must be closed inside the element that it was opened in. This means that any element (except the root node of course) has one and only one <strong>parent element</strong>. If you are modelling structured data it is unlikely you&#8217;ll run into troubles.</p>
<p>Finally I&#8217;ve also added a comment to remind me to add authors to the comments. We won&#8217;t actually be doing this, it was merely there to demonstrate how you can include <strong>comments</strong> in your XML documents. Comments should be ignored when parsing an XML file as they are unrelated to the data. Comments begin with <code class="prettyprint">&lt;!--</code> and end with <code class="prettyprint">--&gt;</code>.</p>
<p>Ok, so by now you should know enough about XML to understand how we can parse this XML file and pull the necessary elements.</p>
<h3>Now for the exciting stuff</h3>
<p>LINQ to XML is a set of classes designed to work well with LINQ. It provides a very simple API that allows XML to be read and written with ease.</p>
<p>The centre of your LINQ to XML world is <code class="prettyprint">XElement</code>. Through <code class="prettyprint">XElement</code> we can access all of the important information in the sample above. Let&#8217;s start by writing a query that can help us get the Blog entries to display on the front page. We&#8217;ll assume I&#8217;ve loaded the XML as a string into a variable called <code class="prettyprint">blogXml</code>.</p>
<pre class="prettyprint">var blog = XElement.Parse(blogXml);

var frontPage = from e in blog.Descendants("Entry")
                where e.Attribute("Archived").Value == "false"
                select e;

foreach (var entry in frontPage)
{
   WriteBlogTitle(entry.Element("Title").Value);
   WriteBlogBody(entry.Element("Body").Value);
   WriteBlogCommentCount(entry.Descendants("Comment").Count());
}</pre>
</p>
<p>This example does absolutely no error checking (something you&#8217;ll definitely want to do if you are working with real XML) but demonstrates how simple it is to find particular elements inside XML. Additionally you can use <code class="prettyprint">XElement</code> objects to pass XML fragments around your application. We could have made our LINQ query return an anonymous type that pulled out the Title, Body and Comment count for each entry, but instead we just pulled out the <code class="prettyprint">XElement</code> itself. From there we were able count the comments inside our loop. </p>
<p>There is nothing preventing you from using these fantastic classes without having to use LINQ queries as well. In fact, most of the XML parsing code I&#8217;ve written lately doesn&#8217;t use LINQ queries at all to find elements, just the methods of the XElement class. Let&#8217;s look at the ones you&#8217;ll likely use most. Don&#8217;t worry that these parameters take an XName as their parameter, strings are automatically cast to a XName. You&#8217;ll need to use XName if you are dealing with namespaces (which I&#8217;ll discuss in a future post).</p>
<ul>
<li><code class="prettyprint"><strong>Element(XName name)</strong></code> returns the first <strong>immediate</strong> child element with the given name. If the element does not exist it returns <code class="prettyprint">null</code>.
</li>
<li><code class="prettyprint"><strong>Elements()</strong></code> returns an <code class="prettyprint">IEnumerable&lt;XElement&gt;</code> of all the <strong>immediate</strong> child elements. So against Blog the enumeration would yield a single &#8220;Entries&#8221; <code class="prettyprint">XElement</code>. If there are no child elements the enumeration will be empty.
</li>
<li><code class="prettyprint"><strong>Elements(XName name)</strong></code> returns an <code class="prettyprint">IEnumerable&lt;XElement&gt;</code> of all the <strong>immediate</strong> child elements with the given name. If no elements with the name exist it will return an empty enumeration.
</li>
<li><code class="prettyprint"><strong>Attribute(XName name)</strong></code> returns an <code class="prettyprint">XAttribute</code> that is the attribute with the specified name. If the attribute does not exist it returns <code class="prettyprint">null</code>.</li>
</ul>
<p>To match the <code class="prettyprint">Element()</code> and <code class="prettyprint">Elements()</code> methods there are also a set of <code class="prettyprint">Descendant()</code> and <code class="prettyprint">Descendants()</code> methods. These work in the same way except that they return all elements under the node. We used this method when we were finding the Entry element as we didn&#8217;t care about the rest of the document&#8217;s hierarchy.</p>
<p>Because these methods return null if the element (or attribute) is not found it is important to check that the value is not null unless you are using a method which returns an <code class="prettyprint">IEnumerable&lt;T&gt;</code> object.</p>
<h3>Where to from here?</h3>
<p>You now know all the important classes needed to parse XML files (perhaps to load up some strongly typed objects). In my next post I&#8217;ll be discussing how you can use this same class to build complex XML structures. In the meantime, check out the <a href="http://msdn.microsoft.com/">MSDN</a> documentation for <code class="prettyprint">XElement</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/25/xml-made-easy-with-linq-to-xml/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>An Introduction to LINQ to SQL</title>
		<link>http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/</link>
		<comments>http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/#comments</comments>
		<pubDate>Mon, 23 Feb 2009 23:23:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/</guid>
		<description><![CDATA[So we already know that LINQ gives us a way to compose queries against IEnumerable&#60;T&#62; objects. LINQ to SQL gives us a way to describe our database so that we can use LINQ queries against the data and have LINQ to SQL generate the necessary SQL statements to get the results. With LINQ to SQL [...]]]></description>
			<content:encoded><![CDATA[<p>So we already know that LINQ gives us a way to compose queries against <code class="prettyprint">IEnumerable&lt;T&gt;</code> objects. LINQ to SQL gives us a way to describe our database so that we can use LINQ queries against the data and have LINQ to SQL generate the necessary SQL statements to get the results. With LINQ to SQL you can query, insert and delete data all with fully compiled LINQ queries. Although LINQ to SQL will take a back seat to the Entity Framework (I&#8217;ll cover that in a future post) according to the ADO.Net team blog&#8217;s &#8220;<a href="http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx">Update on LINQ to SQL and LINQ to Entities Roadmap</a>&#8220;, LINQ to SQL remains a good simple way to set up a database.</p>
<p>I&#8217;ll just be covering the core concepts here. Each of these core concepts will still apply to LINQ to Entities although there are sure to be small differences.</p>
<h3></h3>
<h3>Basic structure</h3>
<p>In Visual Studio LINQ to SQL comes with a full designer experience. You&#8217;ll find &#8220;LINQ to SQL Classes&#8221; as an item under &#8220;Data&#8221; in the Add New Item dialog. Keep in mind that &#8220;DataContext&#8221; will be added to the end of the name you give. I&#8217;ve created many TestDataDataContext classes!</p>
<p>Once this item has been added you will be presented with a designer window. Assuming you are using a SQL Server or SQL Express database you can simply drag tables from the Server Explorer to the designer window (I&#8217;ll be discussing the tool <code>sqlmetal.exe</code> in a future post which can be used to get LINQ to SQL working with SQL Server Compact Edition). As you add more tables, the relationships will begin to appear. Dragging all these tables simply generates extra classes under the scenes. There are four important files that are part of the LINQ to SQL classes:</p>
<ul>
<li><strong>TestDataContext.dbml</strong> is the core file. It is an XML formatted file that describes the tables and relationships in your Data Context.  </li>
<li><strong>TestDataContext.dbml.layout</strong> is purely for the designer experience so that you can lay out your tables in a way that makes sense to you.  </li>
<li><strong>TestDataContext.designer.cs</strong> is where things get interesting. This is the file that contains all the classes that are generated from your .dbml file. These are partial classes so you can add extra methods and properties in a separate file.  </li>
<li><strong>TestDataContext.cs</strong> is the file where you put your extra methods and properties.</li>
</ul>
<p>Each of the tables is represented as a class in your object model. The fields of the tables become the properties and relationships are also represented as properties. It is important to remember that the classes represent a single row from the database.</p>
<p>In addition to the classes representing your data model you also get a DataContext class (in this example TestDataContext) which you use to interact with your database. It has a property for each of your tables which are of type <code class="prettyprint">System.Data.Linq.Table&lt;T&gt;</code> where <code class="prettyprint">T</code> is the name of your class. So if you have a table of Users, you might call the class User (as it represents one user) and your DataContext would have a property Users of type <code class="prettyprint">System.Data.Linq.Table&lt;User&gt;</code>.</p>
<h3>Initialize your DataContext</h3>
<p>All access to your data is done through the DataContext object. Before you can begin you&#8217;ll need to create an instance of the class. If you&#8217;ve used Visual Studio to connect to SQL Server or SQL Express database you probably have access to the default constructor which will use the connection string from your app.config file. If you&#8217;ve used <code>sqlmetal.exe</code> or if you want to manually specify a connection string you can use a simple constructor that just takes the connection string.</p>
<p>In the next examples, we&#8217;ll assume we have already initialized the data context using the connection string from app.config like so:</p>
<pre class="prettyprint">var db = new TestDataContext();</pre>
<h3>Query the database (<code class="prettyprint">SELECT</code>)</h3>
<p>Let&#8217;s start with a simple query to pull data from the database. Let&#8217;s say that we have a really simple blog with the following tables: Entries, Comments and Users. We&#8217;ll be using this same basic database through all of the following examples.</p>
<p>Let&#8217;s start with the front page. Because this is a simple blog all the posts will stay on the front page until we archive them. So we want to start by finding all the blog posts that haven&#8217;t been archived. Let&#8217;s start by looking at the raw SQL.</p>
<pre class="prettyprint">SELECT *
FROM Entries
WHERE e.Archived = 0</pre>
<p>That&#8217;s a pretty simple query and in LINQ it is also simple:</p>
<pre class="prettyprint">var frontPage = from e in db.Entries
                where !e.Archived
                select e;</pre>
<p>Again, this is just our query definition, this line of code will not execute the query against the database. To actually execute the query we need to do something like this:</p>
<pre class="prettyprint">foreach (var entry in frontPage)
{
   WriteBlogTitle(entry.Title);
   WriteBlogBody(entry.Body);
   // TODO: Show number of comments
}</pre>
<p>Here <code class="prettyprint">WriteBlogTitle()</code> and <code class="prettyprint">WriteBlogBody()</code> methods are responsible for sending the output to the web browser. Both methods just take a <code class="prettyprint">string</code> and are completely unaware of where the data is coming from.</p>
<p>I&#8217;ve included a TODO comment suggesting it might be good to show the number of comments for each entry. First I&#8217;ll show you how to do this by running an extra query for each entry:</p>
<pre class="prettyprint">foreach (var entry in frontPage)
{
   WriteBlogTitle(entry.Title);
   WriteBlogBody(entry.Body);
   WriteBlogCommentCount(entry.Comments.Count);
}</pre>
</p>
<p>Because comments are associated with the entry we can directly access its count. This line will cause another database query so has obvious performance implications (as it needs to hit the database server for every single post). Instead we&#8217;ll rewrite the query so we pull everything we need from the database in one query.</p>
<pre class="prettyprint">var frontPage = from e in db.Entries
                where !e.Archived
                select new {
                              Entry = e,
                              CommentCount = e.Comments.Count
                           };

foreach (var post in frontPage)
{
   WriteBlogTitle(post.Entry.Title);
   WriteBlogBody(post.Entry.Body);
   WriteBlogCommentCount(post.CommentCount)
}</pre>
<p>By creating a new anonymous type in the query we send one complex query to the database instead of lots of simple queries.</p>
<p>So what if a user actually wants to view those comments. This time we&#8217;ll accept that two database queries is acceptable (it&#8217;s a constant). So, let&#8217;s see how that might work for a page that displays a specific post.</p>
<pre class="prettyprint">var post = (from e in db.Entries
            where e.Id == id
            select e).FirstOrDefault();

if (post == null)
{
   // Post could not be found
   throw new ArgumentException();
}

WriteBlogTitle(post.Title);
WriteBlogBody(post.Body);

foreach (var comment in post.Comments)
{
   WriteBlogComment(comment.Comment);
}</pre>
<p>It almost seems to easy to believe. Because the relationships are already defined LINQ to SQL is able to generate the second SQL statement to get each of the comments for that post. Most importantly we did all this without any strings!</p>
<h3>Inserting data (<code class="prettyprint">INSERT</code>)</h3>
<p>Right now the blog is pretty boring, it can display posts and comments, but how do the posts and comments get there?&nbsp; Let&#8217;s start with the simple example of creating a post.</p>
<pre class="prettyprint">var post = new Entry();

post.Title = "My first post";
post.Body = "I love LINQ. It's the best.";

db.Entries.InsertOnSubmit(post);
db.SubmitChanges();</pre>
</p>
<p>That&#8217;s it. The post is now in the database. What about a comment?</p>
<pre class="prettyprint">var comment = new Comment();

comment.Comment = "I love LINQ more";
comment.Entry = post;

db.Comments.InsertOnSubmit(comment);
db.SubmitChanges();</pre>
</p>
<p>We&#8217;ve been able to link the comment to the post by using the Entry property directly. We haven&#8217;t had to worry about how our tables are related in our code.</p>
<h3>Deleting data (<code class="prettyprint">DELETE</code>)</h3>
<p>Did you get a spam comment on your blog? Don&#8217;t worry, LINQ to SQL can help you delete it. It follows a similar model to that of inserting data.</p>
<pre class="prettyprint">db.Comments.DeleteOnSubmit(comment);
db.SubmitChanges();</pre>
<h3>Updating data (<code class="prettyprint">UPDATE</code>)</h3>
<p>Maybe you want to start cleaning up the front page because it is starting to get cluttered. We need to update the Archived field on each of the entries we want to archive. To keep things really simple, we&#8217;ll archive all the posts that aren&#8217;t already archived.</p>
<pre class="prettyprint">var toArchive = from e in db.Entries
                where !e.Archived
                select e;

foreach (var entry in toArchive)
{
   entry.Archived = true;
}

db.SubmitChanges();</pre>
<h3>Remember to submit your changes</h3>
<p>The key thing to remember when manipulating data with LINQ to SQL is to call <code class="prettyprint">SubmitChanges()</code> on your DataContext object. Only then will the SQL statements be generated and executed on the server.</p>
<h3>What&#8217;s next?</h3>
<p>In my next LINQ post I&#8217;ll be exploring LINQ to XML.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/24/an-introduction-to-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Introduction to Lambda Expressions in LINQ</title>
		<link>http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/</link>
		<comments>http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 22:33:09 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[lambda]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/</guid>
		<description><![CDATA[Lambda expressions are a great way to write simple anonymous delegates in a concise way. Of course you aren&#8217;t limited to simple functions, you can write a full blown method in lambda syntax. I&#8217;ve already shown some lambda expressions in use when I discussed extensions methods. Here&#8217;s the example: items.Where(item =&#62; item.Price &#60; 1).Select(item =&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Lambda expressions are a great way to write simple <strong>anonymous delegates</strong> in a concise way. Of course you aren&#8217;t limited to simple functions, you can write a full blown method in lambda syntax.</p>
<p>I&#8217;ve already shown some lambda expressions in use when I discussed <a href="http://www.i-think22.net/archives/2009/02/16/linq-and-extension-methods/">extensions methods</a>. Here&#8217;s the example:</p>
</p>
<pre class="prettyprint">items.Where(item =&gt; item.Price &lt; 1).Select(item =&gt; item.Name)</pre>
</p>
<p>There are two lambda expressions in the above example. They are:</p>
<ol>
<li><code class="prettyprint">item =&gt; item.Price &lt; 1</code>
</li>
<li><code class="prettyprint">item =&gt; item.Name</code></li>
</ol>
<p>These are very simple lambda expressions that take one parameter (<code class="prettyprint">item</code>) and return a result. The type of the parameter and the the type of the result are <strong>inferred</strong> by the compiler allowing us to express what clearly without having to decorate it with types. So each of the expressions really means the following:</p>
<ol>
<li>Take an item and return whether the item&#8217;s price is less than one.
</li>
<li>Take and item and return the item&#8217;s name.</li>
</ol>
<p>Hopefully you can see the basic pattern here. Take what&#8217;s on the left of the lambda operator (<code class="prettyprint">=&gt;</code>), use it in the expression on the right and return the result of the expression.</p>
<p>The important thing to remember with lambdas is that they only declare the function. In the example above the lambda expression is executed within the <code class="prettyprint">Where</code> and <code class="prettyprint">Select</code> methods and is executed once for each item in the enumeration. The <code class="prettyprint">Where</code> method uses the result of the lambda expression to determine if the item should be in the resultant enumeration and the <code class="prettyprint">Select</code> method returns the result on the lambda expression as the member of the enumeration.</p>
<h3><code class="prettyprint">Invoke()</code> made easy</h3>
<p>Lambdas aren&#8217;t restricted to being used just with LINQ, they can be used anywhere that anonymous delegates can be found. One area I&#8217;ve found lambdas increasingly useful is in multi-threaded applications. For example, my <a href="http://www.i-think22.net/archives/2009/01/06/tweet-demo/">Tweet demo</a> uses multiple threads to perform the animation. Consequently I often needed to update the UI from the background thread. Because this isn&#8217;t directly allowed I needed to send the code to the UI thread. Before anonymous delegates I would need to create a full blown method to perform a single task. That&#8217;s a lot of extra work for something that is unlikely to be re-used elsewhere. With anonymous delegates I can define the method inline, which is great, but still uses a lot of extra decoration. Now with lambdas I can finally get to the work of just having my code. Here&#8217;s an example straight from that demo.</p>
<pre class="prettyprint">Dispatcher.BeginInvoke(() =&gt;
                           {
                              info.Text = title;
                              infoContainer.Visibility =
                                 Visibility.Visible;
                              _mutex.Unlock();
                           });</pre>
<p>Perhaps the most interesting part of the code is the use of the <code class="prettyprint">title</code> variable within the lambda expression. In this instance, <code class="prettyprint">title</code> is a local variable within the method that is calling <code class="prettyprint">BeginInvoke()</code>. The anonymous delegate will use this local reference when it is called. You can&#8217;t always get away with this.&nbsp; Fortunately strings are immutable in .NET, so we can be confident that the value will not change. If title was mutable (can be changed) its value could be modified after <code class="prettyprint">BeginInvoke()</code> is called, but before it is used in the lambda expression. This may lead to unexpected results.</p>
<p>This problem isn&#8217;t just isolated to multi-threaded applications (although multi-threaded applications are inherently more unpredictable). Because LINQ queries are not executed until they are enumerated (<a href="http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/">LINQ and Deferred Execution</a>) they are susceptible to the same problems, but fortunately in a more consistent way. So remember to always be wary when using a local variable in a LINQ query.</p>
<h3>Generic Delegates in .NET 3.5</h3>
<p>Version 3.5 of the .NET Framework introduced some new generic delegates designed to cover most cases. In fact, it is unlikely that you will need to define your own delegates unless you need more than four parameters.</p>
<p><strong>The <code class="prettyprint">Action</code> delegates</strong></p>
<p><code class="prettyprint">Action</code> delegates refer to a method that does not return a value (a <code class="prettyprint">void</code> method).</p>
<ul>
<li><code class="prettyprint">Action</code> is non-generic delegate that takes no parameters and does not return a value.
</li>
<li><code class="prettyprint">Action&lt;T&gt;</code> was originally introduced in .NET 2.0. This delegate takes one parameter of type <code class="prettyprint">T</code>.
</li>
<li><code class="prettyprint">Action&lt;T1, T2&gt;</code>, <code class="prettyprint">Action&lt;T1, T2, T3&gt;</code> and <code class="prettyprint">Action&lt;T1, T2, T3, T4&gt;</code> are generic delegates that take two, three and four parameters respectively and do not return a value.</li>
</ul>
<p><strong>The <code class="prettyprint">Func</code> delegates</strong></p>
<p><code class="prettyprint">Func</code> delegates are similar to the Action delegates except that they also return a value. The type of the value is always the last type parameter of the generic delegate.</p>
<ul>
<li><code class="prettyprint">Func&lt;TResult&gt;</code> is a generic delegate that takes no parameters and returns a value of type <code class="prettyprint">TResult</code>.
</li>
<li><code class="prettyprint">Func&lt;T, TResult&gt;</code>, <code class="prettyprint">Func&lt;T1, T2, TResult&gt;</code>, <code class="prettyprint">Func&lt;T1, T2, T3, TResult&gt;</code> and <code class="prettyprint">Func&lt;T1, T2, T3, T4, TResult&gt;</code> are generic delegates that take one, two, three and four parameters respectively and return a value of type <code class="prettyprint">TResult</code>.</li>
</ul>
<h3>What&#8217;s next?</h3>
<p>Next up we&#8217;ll be looking at LINQ to SQL and how it can make accessing and using a database a joy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/21/an-introduction-to-lambda-expressions-in-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ and Deferred Execution</title>
		<link>http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/</link>
		<comments>http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 00:25:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/</guid>
		<description><![CDATA[One of the stumbling blocks on the road to understanding LINQ is deferred execution. The key to getting past this is being able to identify that a query is a definition of what you want, rather than the results themselves. Here&#8217;s an example of how this works: var itemsInStock = from item in warehouse.Items where [...]]]></description>
			<content:encoded><![CDATA[<p>One of the stumbling blocks on the road to understanding LINQ is deferred execution. The key to getting past this is being able to identify that a query is a <strong>definition</strong> of what you want, rather than the <strong>results</strong> themselves.</p>
<p>Here&#8217;s an example of how this works:</p>
<pre class="prettyprint">var itemsInStock = from item in warehouse.Items
                   where item.Quantity &gt; 0;
                   select item;

// Display how many items are in stock
Console.WriteLine("Items in stock: {0}", itemsInStock.Count());

// Add a new item to the warehouse
warehouse.Items.Add(new Item("A new item", 50);

// Display how many items are in stock
Console.WriteLine("Items in stock: {0}", itemsInStock.Count());
</pre>
<p>The second time <code class="prettyprint">itemsInStock.Count()</code> is called it returns the updated count that includes our new item. Instead of executing the query when it is defined, execution is <strong>deferred</strong> until a result is needed (such as iterating over the collection with a <code class="prettyprint">foreach</code> loop, using <code class="prettyprint">ToList()</code> to store the results in a <code class="prettyprint">List&lt;T&gt;</code> or one of the many LINQ extension methods that force an actual result (such as <code class="prettyprint">Count()</code> in this example). This has the added benefit of allowing a query to be extended like so:</p>
<pre class="prettyprint">var lowStock = from item in itemsInStock
               where item.Quantity &lt; 5;
               select item;</pre>
<p>This query can now be used to return items that are in stock, but have less than 5 available units.</p>
<p>Quite often you&#8217;ll want to work with a snapshot of the results from a query. Maybe you are writing a method that returns a particular set of items. In this scenario it may be better to return a list rather than the query itself. By returning a list, the calling code is able to iterate over the result multiple times without the result changing. For example you might implement your method like this:</p>
<pre class="prettyprint">private IEnumerable&lt;Item&gt; GetItemsInStockQuery()
{
   return from item in warehouse.Items
          where item.Quantity &gt; 0
          select item;
}

public List&lt;Item&gt; GetItemsInStock()
{
   return GetItemsInStockQuery().ToList();
}</pre>
<p>Calling code is able to get the information it needs and internally you can directly get access to the query.</p>
<p>Another important thing to remember is that because a query is executed every time you iterate it with a <code class="prettyprint">foreach</code> loop you should use <code class="prettyprint">ToList()</code> if you are repeatedly calling the query and don&#8217;t need the results to be recalculated each time.</p>
<h3>More LINQ to come</h3>
<p>In my next post I&#8217;ll explore lambda expressions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/18/linq-and-deferred-execution/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ and Extension methods</title>
		<link>http://www.i-think22.net/archives/2009/02/16/linq-and-extension-methods/</link>
		<comments>http://www.i-think22.net/archives/2009/02/16/linq-and-extension-methods/#comments</comments>
		<pubDate>Sun, 15 Feb 2009 21:44:00 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/16/linq-and-extension-methods/</guid>
		<description><![CDATA[Have you ever wished that a base class had a particular method? What about interfaces? Wouldn&#8217;t it be great to define a method on an interface along with its implementation? Any class that then implemented the interface would get this implementation for free. In the past this was achieved with static utility classes. Unfortunately this [...]]]></description>
			<content:encoded><![CDATA[<p>Have you ever wished that a base class had a particular method? What about interfaces? Wouldn&#8217;t it be great to define a method on an interface along with its implementation? Any class that then implemented the interface would get this implementation for free.</p>
<p>In the past this was achieved with static utility classes. Unfortunately this leads to cluttering your code with the names of these utility classes and dilute the expressiveness of your code. Let&#8217;s say we have a utility class the gets the words and word count from a string. Don&#8217;t worry too much about the implementation, just the general structure.</p>
<pre class="prettyprint">public static class StringUtilities
{
   private static readonly Regex wordsRegex = new Regex(@"\w+");

   public static IEnumerable&lt;string&gt; GetWords(string source)
   {
      return from word in wordsRegex.Matches(source).Cast&lt;Match&gt;()
             select word.Value;
   }

   public static int WordCount(string source)
   {
      return GetWords(source).Count();
   }
}</pre>
<p>To use this in our code we would have to do something like this:</p>
<pre class="prettyprint">var sentence = "The quick brown fox jumps over the lazy dog";

// Display each of the words
foreach (var word in StringUtilities.GetWords(sentence))
{
   Console.WriteLine(word);
}

// Display the word count
Console.Write("Total Words: ")
Console.WriteLine(StringUtilities.WordCount(sentence));</pre>
<p>Look at all that clutter. The truth in this context is that we are really performing an action on the sentence. Wouldn&#8217;t it be better if we could just call <code class="prettyprint">sentence.GetWords() </code>or <code class="prettyprint">sentence.WordCount() </code>instead? It would certainly be more readable. Extension methods make this all possible. Here&#8217;s our updated StringUtilities class that creates the extension methods:
<pre class="prettyprint">public static class StringUtilities
{
   private static readonly Regex wordsRegex = new Regex(@"\w+");

   public static IEnumerable&lt;string&gt; GetWords(<strong>this</strong> string source)
   {
      return from word in wordsRegex.Matches(source).Cast&lt;Match&gt;()
             select word.Value;
   }

   public static int WordCount(<strong>this</strong> string source)
   {
      return GetWords(source).Count();
   }
}</pre>
</p>
<p>We&#8217;ve added <code class="prettyprint">this</code> before the variable type. The rest of the code has been left untouched. So now we can use the extension methods like so:</p>
<pre class="prettyprint">var sentence = "The quick brown fox jumps over the lazy dog";

// Display each of the words
foreach (var word in sentence.GetWords())
{
   Console.WriteLine(word);
}

// Display the word count
Console.WriteLine("Total Words: {0}", sentence.WordCount());</pre>
<p>Doesn&#8217;t that read better? We have been able to push the implementation details (the name of the static utility class) out of our code.</p>
<h3>How to enable an extension method</h3>
<p>In order to use an extension method it must be part of the local namespace or imported with a <code class="prettyprint">using</code> statement. Once that&#8217;s done you can call extension methods just as you would any normal method.</p>
<h3></h3>
<h3>What does this have to do with LINQ?</h3>
<p>LINQ is all about extension methods. When you import the System.Linq namespace it comes with a whole bundle of extension methods. Most of them act on <code class="prettyprint">IEnumerable&lt;T&gt;</code> and can be used to write your LINQ queries in method syntax. Let&#8217;s look at this query:</p>
<pre class="prettyprint">from item in items
where item.Price &lt; 1
select item.Name</pre>
</p>
<p>This query finds the items that are under one dollar and returns their names. We can write this query in method syntax like so:</p>
<pre class="prettyprint">items.Where(item =&gt; item.Price &lt; 1).Select(item =&gt; item.Name)</pre>
<p>It&#8217;s not quite as readable (although that is a matter of opinion), but it gives a good indication of what is going on (and further demonstrates why select is at the end). These methods also take advantage of Lambda expressions (which I&#8217;ll discuss in a future post).</p>
<p>There are other useful extension functions that work with queries. Some of the ones you&#8217;ll use most often are:</p>
<ul>
<li><code class="prettyprint"><strong>ToList()</strong></code> executes the query and returns the results in a list. You will probably use this method a lot. I&#8217;ll cover this method an its consequences in more depth in a future post on deferred execution.
</li>
<li><code class="prettyprint"><strong>Count()</strong></code> executes the query and returns the number of results. When used with LINQ to SQL it will execute SQL code to get the database server to return the count.
</li>
<li><code class="prettyprint"><strong>Any()</strong></code> returns <code class="prettyprint">true</code> if there are any results in the query. Use this instead of Count() &gt; 0 to abstract out the implementation detail.
</li>
<li><code class="prettyprint"><strong>First()</strong></code> returns the first result from the query. This is particularly useful when you have a query that will only return one result (such as looking up an entry based on its primary key). This method will throw an exception (<code class="prettyprint">InvalidOperationException</code>) if the query yields no results.
</li>
<li><code class="prettyprint"><strong>FirstOrDefault()</strong></code> returns the first result from the query, much like First(). If there are no results it will return the default for the type (e.g. <code class="prettyprint">0</code> for an <code class="prettyprint">int</code>, <code class="prettyprint">null</code> for reference types).</li>
</ul>
<p>Fortunately you aren&#8217;t limited to using these extension methods on LINQ queries. They are designed to work on any class that implements <code class="prettyprint">IEnumerable&lt;T&gt;</code>. This means you can use them directly on a lot of the classes already in the .NET base class library.</p>
<h3>What about old non-generic <code class="prettyprint">IEnumerable</code>?</h3>
<p>There are a lot of classes in the .NET framework that don&#8217;t implement <code class="prettyprint">IEnumerable&lt;T&gt;</code> but instead implement the non-generic interface <code class="prettyprint">IEnumerable</code>. A perfect example is <code class="prettyprint">MatchCollection</code> used by Regular expressions. When we enumerate over a <code class="prettyprint">MatchCollection</code> we are given the base <code class="prettyprint">object</code> which we then need to cast to a <code class="prettyprint">Match</code> object. Until we do this cast we can&#8217;t access any of the properties of <code class="prettyprint">Match</code>. Fortunately there are a couple of LINQ extension methods designed to help out when dealing with IEnumerable.</p>
<ul>
<li><code class="prettyprint"><strong>Cast&lt;T&gt;()</strong></code> returns a strongly typed <code class="prettyprint">IEnumerable&lt;T&gt;</code> object. Each object is cast to the type <code class="prettyprint">T</code>. If an object can&#8217;t be cast an exception is thrown (<code class="prettyprint">InvalidCastException</code>). In the case of a <code class="prettyprint">MatchCollection</code> I am confident that every object is a <code class="prettyprint">Match</code> object and an exception won&#8217;t be thrown.
</li>
<li><code class="prettyprint"><strong>OfType&lt;T&gt;()</strong></code> also returns a strongly typed <code class="prettyprint">IEnumerable&lt;T&gt;</code> object. It goes further than <code class="prettyprint">Cast&lt;T&gt;()</code> by only including objects of that type in the enumeration. In other words it filters out any class that isn&#8217;t of the desired type (without throwing exceptions). This is the method to use when you are unsure of what the type will be or if you are dealing with an enumeration that contains different typed objects.</li>
</ul>
<p>If you want to see <code class="prettyprint">OfType&lt;T&gt;()</code> in action, copy and paste the following example into <a href="http://www.linqpad.net/">LINQPad</a>. (You&#8217;ll need to select C# Statement(s) from the language drop down).</p>
<pre class="prettyprint">var items = new object[]{"a string", 22, Math.PI};

items.OfType&lt;string&gt;().Dump("OfType&lt;string&gt;");
items.OfType&lt;int&gt;().Dump("OfType&lt;int&gt;");
items.OfType&lt;double&gt;().Dump("OfType&lt;double&gt;");</pre>
</p>
<p>LINQPad has its own extension method <code class="prettyprint">Dump()</code> which is used to output results to the LINQPad window. You&#8217;ll see that each individual dump returns a strongly typed <code class="prettyprint">IEnumerable&lt;T&gt;</code> object. In this example items actually implemented <code class="prettyprint">IEnumerable&lt;object&gt;</code>. Fortunately these methods don&#8217;t discriminate and happily work their magic on any <code class="prettyprint">IEnumerable&lt;T&gt;</code> as well.</p>
<h3>Still more to come</h3>
<p>There is still plenty of more that I will post about LINQ. In my next post I&#8217;ll look at deferred execution, what it means and how you can take advantage of it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/16/linq-and-extension-methods/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Getting Started with LINQ</title>
		<link>http://www.i-think22.net/archives/2009/02/14/getting-started-with-linq/</link>
		<comments>http://www.i-think22.net/archives/2009/02/14/getting-started-with-linq/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 05:27:39 +0000</pubDate>
		<dc:creator>Rhys</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[vsexpress]]></category>
		<category><![CDATA[vstudio]]></category>

		<guid isPermaLink="false">http://www.i-think22.net/archives/2009/02/14/getting-started-with-linq/</guid>
		<description><![CDATA[I really like LINQ. It&#8217;s one of my favourite .NET features. When I first heard about it I was doing most of my programming in Visual Basic 6 (or worse, Visual Basic for Applications). Working now with C# and the .NET Framework has blessed me with full O-O, strong types, an excellent base class library, [...]]]></description>
			<content:encoded><![CDATA[</p>
<p>I really like LINQ. It&#8217;s one of my favourite .NET features. When I first heard about it I was doing most of my programming in Visual Basic 6 (or worse, Visual Basic for Applications). Working now with C# and the .NET Framework has blessed me with full O-O, strong types, an excellent base class library, Visual Studio 2008 (and IntelliSense), Generics (I love generics) and LINQ.</p>
<p>So what is LINQ and why is it so important to add to your arsenal of .NET skills?</p>
<h3></h3>
<h3>LINQ is so many things</h3>
<p>At its core LINQ is exactly what its acronym suggests: Language Integrated Query. But what does this actually mean? Is it just some marketing hype designed to confuse the masses and look good on your resume. Probably. But the value of expressing a query concisely in the language of your choice becomes more apparent with each LINQ query you write. (Yes, I know LINQ Query would stand for Language Integrated Query query. Just go with it, it reads better.)</p>
<p>Importantly a LINQ query separates defining what you are looking for from how to find it. This means that a LINQ query could potentially be executed across multiple CPU cores and in the case of LINQ to SQL can be turned into an efficient SQL query so the hard work can be done by your database server.</p>
<p>But when are you going to actually use LINQ? Chances are good that you already have some code that could benefit from a bit of LINQ.</p>
<p>Take this example:</p>
<pre class="prettyprint">var itemsUnderOneDollar = new List&lt;Item&gt;();
foreach (var item in items)
{
   if (item.Price &lt; 1)
   {
      itemsUnderOneDollar.Add(item);
   }
}</pre>
<p>In this case we want to find all items that are under one dollar. The same in LINQ would be:</p>
<pre class="prettyprint">var itemsUnderOneDollar = (from item in items
                           where item.Price &lt; 1
                           select item).ToList();</pre>
<p>We can ignore the variable declaration for now (and the call to <code class="prettyprint">ToList()</code>) so let&#8217;s break it down to just the core LINQ query.</p>
<pre class="prettyprint">from item in items
where item.Price &lt; 1
select item</pre>
<p>The LINQ query describes exactly what you want and nothing more. When we used the <code class="prettyprint">foreach</code> construct we were resigned to the fact that we had to look at each and every item. We are also doing all this in a single thread. In fact, we spend more time describing <strong>how</strong> we want to find the items than saying <strong>what</strong> it is that we want. By describing what we want using LINQ we don&#8217;t bother with the implementation details resulting in <strong>cleaner code</strong> and improved <strong>flexibility</strong> for how the query should be implemented. In the case of a database query, the ideal implementation would be to generate a SQL query, execute the SQL query against the database and return the results. LINQ to SQL does just that with essentially the same code (Iâ€™ll be discussing LINQ to SQL in depth in another post).</p>
<h3>From Where Select vs. Select From Where</h3>
<p>If you are already familiar with SQL you may be a little confused by the syntax of a LINQ query. Indeed this is a major stumbling block most people encounter when they start to use LINQ. In SQL we have the &#8216;select&#8217; statement upfront but in LINQ we save it for the end. Why? The primary reason for this choice was to enable great IntelliSense support in Visual Studio. </p>
<p>I&#8217;d like to argue that the syntax in LINQ actually makes more sense. Rather than starting with what we want at the end we start with the subject of our query. The reason this seems so foreign is that we are so used to it because of SQL. When you write code you typically say where you want to look before you say what you want to do when you&#8217;ve found it. In natural language it is like saying &#8220;From the store find a computer with 2GiB RAM and get me the price of the computer&#8221;. In SQL speak that would be &#8220;Get the price of the computer in the store where that computer has 2GiB RAM&#8221;. You tell me which form you&#8217;d be more likely to use.</p>
<h3>The magic of type inference</h3>
<p>Another convenient way to remember that <code class="prettyprint">from</code> comes first is to think of the old <code class="prettyprint">foreach</code> implementation. You&#8217;ll find that they have a lot in common. The biggest difference is that in the <code class="prettyprint">foreach</code> loop we have to explicitly specify a type. In the example above I&#8217;ve used <code class="prettyprint">var</code> to let the compiler infer the type. In the LINQ query the type is inferred automatically unless you specify it explicitly.</p>
<p>Type inference is used throughout most LINQ usage to simplify code and to improve maintainability. Queries return an object that implements the <code class="prettyprint">IEnumerable&lt;T&gt;</code> interface. More advanced queries can return objects that implement a more complex interface (which is also an <code class="prettyprint">IEnumerable&lt;T&gt;</code>). By using <code class="prettyprint">var</code> to let the compiler infer the type of object returned by the query it saves the programmer from having to explicitly work out what type of object is returned. The full significance of this will become apparent in future posts.</p>
<h3>How to get started</h3>
<p>The best way to get started working with LINQ is to read up about it on <a href="http://msdn.microsoft.com/">MSDN</a>. Then download the great tool <a href="http://www.linqpad.net/">LINQPad</a>. LINQPad has some great sample LINQ queries and lets you play with LINQ outside of Visual Studio. It&#8217;s great for writing short snippets of code and is an ideal sandbox to try out bits of code. LINQPad is free, but Auto Completion is a paid feature (but well worth it). It also lets you run LINQ to SQL queries on a SQL database (and now SQL Compact Edition).</p>
<p>Once you have started familiarising yourself with LINQ you should start using it in your projects. There are two key requirements to using LINQ:</p>
<ol>
<li>Your project must target version 3.5 of the .NET Framework.
</li>
<li>You must include <code class="prettyprint">using System.Linq;</code> to reference the LINQ namespace in all code files where you want to use LINQ. </li>
</ol>
<p>If you don&#8217;t have Visual Studio 2008 you can download one of the free express editions from <a href="http://www.microsoft.com/express/">http://www.microsoft.com/express/</a>. Once installed you might also want to <a href="http://www.i-think22.net/archives/2008/05/11/line-numbers-in-visual-c-2008-express/">turn on line numbers in Visual C# Express</a>.</p>
<h3>More to come</h3>
<p>There&#8217;s plenty of stuff to talk about with LINQ. In my next few posts I&#8217;ll cover Extensions methods, Lambda expressions, LINQ over objects and much more.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.i-think22.net/archives/2009/02/14/getting-started-with-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
