<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>LINQ Exchange</title>
	
	<link>http://blog.linqexchange.com</link>
	<description>LINQ and Lambda Expressions Explained</description>
	<lastBuildDate>Mon, 26 Jul 2010 08:46:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/LinqExchange" /><feedburner:info uri="linqexchange" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>LinqExchange</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FLinqExchange" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FLinqExchange" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2FLinqExchange" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/LinqExchange" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FLinqExchange" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FLinqExchange" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FLinqExchange" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><item>
		<title>LINQ ToLookup vs ToDictionary</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/PLs4cJdJOYg/</link>
		<comments>http://blog.linqexchange.com/index.php/linq-tolookup-vs-todictionary/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 08:46:08 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[linq c#]]></category>
		<category><![CDATA[todictionary]]></category>
		<category><![CDATA[tolookup]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=157</guid>
		<description><![CDATA[Some people are not sure of the difference between ToLookup vs ToDictionary LINQ methods. To break it down real simple: One is a look up (ToLookup) One is a dictionary (ToDictionary) Duh &#8211; that’s what you’re probably thinking. The real difference is understanding what each of these data structures do. Lookups A lookup is a [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<div>
<p>Some people are not sure of the difference between <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx" target="_blank">ToLookup</a> vs <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx" target="_blank">ToDictionary</a> LINQ methods.</p>
<p>To break it down real simple:</p>
<ul>
<li>One is a look up (ToLookup)</li>
<li>One is a dictionary (ToDictionary)</li>
</ul>
<p>Duh &#8211; that’s what you’re probably thinking. The real difference is understanding what each of these data structures do.</p>
<p><strong>Lookups</strong></p>
<p>A lookup is a key value pair in which multiple keys of the same value  can exist, therefore resulting in a “lookup” type of scenario. The  perfect example for this is to assume that we have a List of Author  objects. The author object contains the following:</p>
<ul>
<li>First Name</li>
<li>Last Name</li>
<li>Year their first book was published</li>
<li>Social Security Number</li>
</ul>
<p>Assume that we’d like to give the user the option to select the  authors based upon the year they published their first book in a WPF  app. We could do that like this:</p>
<blockquote><div>// Returns a list of Authors<br />var authors = authorService.FindAll();</p>
<p>// Turn the list into a lookup for later use<br />var authorLookup = authors.ToLookup(k =&gt; k.YearFirstPublished, v =&gt; v);</p>
<p>// Further down in the code<br />// Find all authors who published their first book in 1969<br />// Returns an enumerable of Authors that match that lookup value<br />var authorsPublishedInParticularYear = authorLookup[1969];</div>
<div></div>
</blockquote>
<div>This will return all authors who published their first book in 1969.  We could use this look up later in the application as well to look up  other values.</div>
<p><em>The key thing to note here is that <strong>a Lookup can have multiple keys of the same value</strong>. <a href="http://msdn.microsoft.com/en-us/library/bb460184.aspx" target="_blank">MSDN</a> states: </em>A Lookup(Of TKey, TElement) resembles a Dictionary(Of TKey, TValue). The difference is that a Dictionary(Of TKey, TValue) maps keys to single values, whereas a Lookup(Of TKey, TElement) maps keys to collections of values.</p>
<p><strong> </strong></p>
<p><strong>Dictionaries</strong></p>
<p>A dictionary is a key value pair in which a key can only exist once  within the dictionary. You cannot have two entries with the same key.  This is the difference between the Dictionary and Lookup data  structures.</p>
<p>Using the same Author object we described above we can find an author  by their Social Security Number if we turned the list into a dictionary  for fast lookups based upon a unique key (the social security number).</p>
<p>This will return a single Author object who’s social security number matches ‘555-55-5555’.</p>
<blockquote><div>// Returns a list of Authors<br />var authors = authorService.FindAll();</p>
<p>// Turn the list into a lookup for later use<br />var authorDictionary = authors.ToDictionay(k =&gt; k.SocialSecurityNumber, v =&gt; v);</p>
<p>// Further down in the code<br />// Finds the author with 555-55-5555 as their Social Security Number<br />var author = authorDictionary["555-55-5555"];</div>
<div></div>
</blockquote>
<div><strong>Conclusion</strong></div>
<p>While dictionaries and lookups seem to be nearly the same data  structure, they provide completely different functionality based upon  the value the key possesses.</p>
</div>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/6PCZS80qcibAP-eltkjoyOn3rUI/0/da"><img src="http://feedads.g.doubleclick.net/~a/6PCZS80qcibAP-eltkjoyOn3rUI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/6PCZS80qcibAP-eltkjoyOn3rUI/1/da"><img src="http://feedads.g.doubleclick.net/~a/6PCZS80qcibAP-eltkjoyOn3rUI/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/linq-tolookup-vs-todictionary/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/linq-tolookup-vs-todictionary/</feedburner:origLink></item>
		<item>
		<title>Implementing LINQ on the .NET Micro Framework</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/dGoMJYJVSAA/</link>
		<comments>http://blog.linqexchange.com/index.php/implementing-linq-on-the-net-micro-framework/#comments</comments>
		<pubDate>Fri, 02 Jul 2010 08:03:09 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[.net micro framework]]></category>
		<category><![CDATA[delegates]]></category>
		<category><![CDATA[lambda expressions]]></category>
		<category><![CDATA[linq c#]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=151</guid>
		<description><![CDATA[The .NET Micro Framework, a variant of .NET radically scaled down for embedded systems, does not include the System.Linq namespace and does not provide any LINQ functionality. Because its implementation is based on generics, LINQ requires version 2.0 of the CLR. The Micro Framework on the other hand is restricted to the CLI, a standardized [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.microsoft.com/netmf">.NET Micro  Framework</a>, a variant of .NET radically scaled down for embedded  systems, does not include the <a href="http://msdn.microsoft.com/en-us/library/system.linq.aspx">System.Linq</a> namespace and does not provide any <a href="http://msdn.microsoft.com/en-us/library/bb308959.aspx">LINQ</a> functionality. Because its implementation is based on generics, LINQ  requires version 2.0 of the CLR. The Micro Framework on the other hand  is restricted to the <a href="http://en.wikipedia.org/wiki/Common_Language_Infrastructure">CLI</a>,  a standardized specification of Microsoft&#8217;s CLR 1.0.</p>
<p>Fortunately, the other relevant language features such as <a href="http://www.google.com/search?q=lambda+expressions">lambda  expressions</a>, <a href="http://www.google.com/search?q=extension+methods">extension  methods</a> and <a href="http://en.wikipedia.org/wiki/List_comprehension">list  comprehension</a> can all be seen as syntactic sugar. Introduced with C#  3.0 &#8211; and due to the genius of Anders Hejlsberg &#8211; those features can be  compiled to IL instructions already implemented by any CLI-compliant  virtual machine. And, as Marc Frei and Cuno Pfister prove with the  following code, the lack of generics barely affects the undeniable  elegance of LINQ.</p>
<blockquote><pre><code>using System.Collections;using Microsoft.SPOT;

namespace System.Runtime.CompilerServices {  [AttributeUsageAttribute(    AttributeTargets.Assembly    | AttributeTargets.Class    | AttributeTargets.Method)]  sealed class ExtensionAttribute: Attribute {}}

delegate bool Predicate (object o);

sealed class Enumerator: IEnumerator {  IEnumerator e;  Predicate p;

  internal Enumerator (IEnumerator e, Predicate p) {    this.e = e;    this.p = p;  }

  object IEnumerator.Current {    get { return e.Current; }  }

  void IEnumerator.Reset () {    e.Reset();  }

  bool IEnumerator.MoveNext () {    var b = e.MoveNext();    while (b &amp;&amp; !p(e.Current)) {      b = e.MoveNext();    }    return b;  }}

sealed class Filter: IEnumerable {  IEnumerable e;  Predicate p;

  internal Filter (IEnumerable e, Predicate p) {    this.e = e;    this.p = p;  }

  IEnumerator IEnumerable.GetEnumerator () {    return new Enumerator(e.GetEnumerator(), p);  }}

static class Program {  static int Count (this IEnumerable e) {    var n = 0;    foreach (var o in e) {      n++;    }    return n;  }

  static IEnumerable Where (this IEnumerable e, Predicate p) {    return new Filter(e, p);  }

  static void Main () {    var a = new int[] {1, 2, 3, 4, 6, 8, 9, 9, 9};    var n = a.Where(v =&gt; (int) v % 2 == 0).Count();    var m = (from v in a where (int) v % 2 == 0 select v).Count();    Debug.Print(n + " " + m);  }}</code></pre>
</blockquote>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/YFXlCFnbpkSdmJUgIq5EcyKdDSs/0/da"><img src="http://feedads.g.doubleclick.net/~a/YFXlCFnbpkSdmJUgIq5EcyKdDSs/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/YFXlCFnbpkSdmJUgIq5EcyKdDSs/1/da"><img src="http://feedads.g.doubleclick.net/~a/YFXlCFnbpkSdmJUgIq5EcyKdDSs/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/implementing-linq-on-the-net-micro-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/implementing-linq-on-the-net-micro-framework/</feedburner:origLink></item>
		<item>
		<title>How to Use .Except with EqualityComparer</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/BTlzkgLoIHQ/</link>
		<comments>http://blog.linqexchange.com/index.php/how-to-use-except-with-equalitycomparer/#comments</comments>
		<pubDate>Fri, 14 May 2010 08:24:14 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[enumerator]]></category>
		<category><![CDATA[EqualityComparer]]></category>
		<category><![CDATA[foreach]]></category>
		<category><![CDATA[ienumerable]]></category>
		<category><![CDATA[linq c#]]></category>
		<category><![CDATA[LINQ Except]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=147</guid>
		<description><![CDATA[Today we&#8217;re going to cover an advanced scenario where we need to compare lists of a class we created. We’ll start with an implementation of EqualityComparer&#60;T&#62; which consists of overriding two methods: Equals and GetHashCode. What was a little tricky about this implementation is this subtle, but critical, comment in the code sample on MSDN [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Today we&#8217;re going to cover an advanced scenario where we need to compare lists of a class we  created. We’ll start with an implementation of <a href="http://msdn.microsoft.com/en-us/library/ms132123.aspx">EqualityComparer&lt;T&gt;</a> which consists of overriding two methods: Equals and GetHashCode.  What  was a little tricky about this implementation is this subtle, but  critical, comment in the code sample on <a href="http://msdn.microsoft.com/en-us/library/bb336390.aspx">MSDN</a> (in the <a href="http://msdn.microsoft.com/en-us/library/bb336390.aspx">Enumerable.Except  documentation</a>):</p>
<blockquote><p>// If Equals() returns true for a pair of objects,      <br />//  GetHashCode must return the same value for these objects.</p>
</blockquote>
<p>// GetHashCode must return the same value for these  objects.</p>
<blockquote><p>public class WidgetComparer : EqualityComparer&lt;Widget&gt;<br /> {<br /> public override bool Equals(Widget x, Widget y)<br /> {<br /> if (ReferenceEquals(x, y)) return true;</p>
<p>return x.Id == y.Id &amp;&amp; x.Name == y.Name &amp;&amp; x.Price == y.Price;<br /> }</p>
<p>public override int GetHashCode(Widget obj)<br /> {<br /> if (ReferenceEquals(obj, null)) return 0;</p>
<p>var nameHash = obj.Name == null ? 0 : obj.Name.GetHashCode();<br /> var idHash = obj.Id.GetHashCode();<br /> var priceHash = obj.Price.GetHashCode();</p>
<p>return nameHash ^ idHash ^ priceHash;<br /> }<br /> }</p>
</blockquote>
<p>Now that we have our EqualityComparer set up for the Widget class,  let’s look at how the Except method uses our implementation.</p>
<p><strong>Test 1 – Two lists with same reference items.</strong></p>
<blockquote><p>[TestMethod]<br /> public void Except_ListsWithSameReferenceItems_ShouldNotYieldDifferences()<br /> {<br /> var widget1 = new Widget { Id = 1, Name = &#8220;Widget1&#8243;,                                       Price = 0.99 };<br /> var widget2 = new Widget { Id = 2, Name = &#8220;Widget2&#8243;,                                        Price = 0.99 };<br /> var list1 = new List&lt;Widget&gt; { widget1, widget2 };<br /> var list2 = new List&lt;Widget&gt; { widget1, widget2 };</p>
<p>var results = list1.Except(list2, new WidgetComparer());</p>
<p>Assert.IsTrue(results.Count() == 0);<br /> }</p>
</blockquote>
<p>Note in our implementation (which follows the example from MSDN) we  check object.ReferenceEquals in the Equals method.  But that check alone  will not suffice, the result from GetHashCode is also validated so we  must calculate the HashCode uniformly for the object as well.</p>
<p><strong>Test 2 – Two lists with same items (but not same references)</strong></p>
<blockquote><p>[TestMethod]<br /> public void Except_ListsWithSameItems_ShouldNotYieldDifferences()<br /> {<br /> var list1 = new List&lt;Widget&gt;<br /> {<br /> new Widget { Id = 1, Name = &#8220;Widget1&#8243;,                                             Price = 0.99 },<br /> new Widget { Id = 2, Name = &#8220;Widget2&#8243;,                                            Price = 0.99 }<br /> };<br /> var list2 = new List&lt;Widget&gt;<br /> {<br /> new Widget { Id = 1, Name = &#8220;Widget1&#8243;,                                            Price = 0.99 },<br /> new Widget { Id = 2, Name = &#8220;Widget2&#8243;,                                            Price = 0.99 }<br /> };</p>
<p>var results = list1.Except(list2, new WidgetComparer());</p>
<p>Assert.IsTrue(results.Count() == 0);<br /> }</p>
</blockquote>
<p>In this test we use widgets set up with identical properties for each  list.  The test will still pass because our EqualityComparer evaluates  the widgets using the formula we specified (Id, Name, &amp; Price all  match).</p>
<p><strong>Test 3 – Two lists with different items.  This one is tricky  though, because it List 2 is the one that contains different items.</strong></p>
<blockquote><p>[TestMethod]<br /> public void Except_List2WithDifferentItems_ShouldNotYieldDifferences()<br /> {<br /> var list1 = new List&lt;Widget&gt; {<br /> new Widget { Id = 1, Name = &#8220;Widget1&#8243;, Price = 0.99 },<br /> new Widget { Id = 2, Name = &#8220;Widget2&#8243;, Price = 0.99 }<br /> };<br /> var list2 = new List&lt;Widget&gt;{<br /> new Widget {Id = 1, Name = &#8220;Widget1&#8243;, Price = 0.99},<br /> new Widget {Id = 2, Name = &#8220;Widget2&#8243;, Price = 0.99},<br /> new Widget { Id = 3, Name = &#8220;Widget3&#8243;, Price = 0.99 }<br /> };</p>
<p>var results = list1.Except(list2, new WidgetComparer());</p>
<p>Assert.IsTrue(results.Count() == 0);<br /> }</p>
</blockquote>
<p>What gives?  When you call Except you are saying “Give me everything  that is in list 1, that is not in list 2.”  In this case, list 2 has  more items than list 1 and all the items from list 1 are in list 2.</p>
<p><strong>Test 4 – Two lists with different items.  This time list 1  has more items than list 2.</strong></p>
<blockquote><p>[TestMethod]<br /> public void Except_List1WithDifferentItems_ShouldYieldDifferences()<br /> {<br /> var list1 = new List&lt;Widget&gt; {<br /> new Widget { Id = 1, Name = &#8220;Widget1&#8243;, Price = 0.99 },<br /> new Widget { Id = 2, Name = &#8220;Widget2&#8243;, Price = 0.99 },<br /> new Widget { Id = 3, Name = &#8220;Widget3&#8243;, Price = 0.99 }<br /> };<br /> var list2 = new List&lt;Widget&gt;{<br /> new Widget {Id = 1, Name = &#8220;Widget1&#8243;, Price = 0.99},<br /> new Widget {Id = 2, Name = &#8220;Widget2&#8243;, Price = 0.99}<br /> };</p>
<p>var results = list1.Except(list2, new WidgetComparer());</p>
<p>Assert.IsTrue(results.Count() == 1);<br /> }</p>
</blockquote>
<p>As expected, we find that Widget3 does not exist in list 2.   Remember, when you call Except, say the mantra: “Give me everything that  is in list 1, that is not in list 2.”</p>
<p>If you have any comments or improvements on this simple example of  using Except, post away!</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/jxv49ufUTZgKlm1unAlCbgJdNPs/0/da"><img src="http://feedads.g.doubleclick.net/~a/jxv49ufUTZgKlm1unAlCbgJdNPs/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/jxv49ufUTZgKlm1unAlCbgJdNPs/1/da"><img src="http://feedads.g.doubleclick.net/~a/jxv49ufUTZgKlm1unAlCbgJdNPs/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/how-to-use-except-with-equalitycomparer/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/how-to-use-except-with-equalitycomparer/</feedburner:origLink></item>
		<item>
		<title>Use LINQ and Reflection to Find Matching Properties</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/Gj7Ztnt9JSQ/</link>
		<comments>http://blog.linqexchange.com/index.php/use-linq-and-reflection-to-find-matching-properties/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 08:06:21 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=142</guid>
		<description><![CDATA[As a side product of some experiments I wrote simple LINQ query that matches properties of two objects and returns these properties as list. The code I wrote is pretty simple and I packed it for you as method. C# public IList GetMatchingProperties(object source, object target) { if (source == null) throw new ArgumentNullException(&#8220;source&#8221;); if [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>As a side product of some experiments I wrote simple LINQ query that matches properties of two objects and returns these properties as list. The code I wrote is pretty simple and I packed it for you as method.</p>
<blockquote><p><strong>C#</strong><br /> public IList GetMatchingProperties(object source, object target)<br /> {<br /> if (source == null)<br /> throw new ArgumentNullException(&#8220;source&#8221;);<br /> if (target == null)<br /> throw new ArgumentNullException(&#8220;target&#8221;);</p>
<p>var sourceType = source.GetType();<br /> var sourceProperties = sourceType.GetProperties();<br /> var targetType = target.GetType();<br /> var targetProperties = targetType.GetProperties();</p>
<p>var properties = (from s in sourceProperties<br /> from t in targetProperties<br /> where s.Name == t.Name &amp;&amp;<br /> s.PropertyType == t.PropertyType<br /> select s).ToList();<br /> return properties;<br /> }</p>
</blockquote>
<blockquote><p><strong>VB.NET</strong><br /> Public Function GetMatchingProperties(ByVal source As Object,_<br /> ByVal target As Object) As IList(Of PropertyInfo)</p>
<p>If source Is Nothing Then<br /> Throw New ArgumentNullException(&#8220;source&#8221;)<br /> End If<br /> If target Is Nothing Then<br /> Throw New ArgumentNullException(&#8220;target&#8221;)<br /> End If</p>
<p> Dim sourceType = source.GetType()<br /> Dim sourceProperties = sourceType.GetProperties()<br /> Dim targetType = target.GetType()<br /> Dim targetProperties = targetType.GetProperties()</p>
<p> Dim properties = (From s In sourceProperties _<br /> From t In targetProperties _<br /> Where s.Name = t.Name AndAlso s.PropertyType = t.PropertyType _<br /> Select s).ToList()<br /> Return properties<br /> End Function</p>
</blockquote>
<p>The method returns only those properties that match by name and type. If both objects have property called Sum and both of them have Sum in different type (let’s say float and decimal) then this property is not returned by this method. Of course, you can extend this method if you like and you can make it much more clever. Simple implementation given here worked for me very well.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/3QdLM2p0dDQRL4VPTNPQeV3MgAw/0/da"><img src="http://feedads.g.doubleclick.net/~a/3QdLM2p0dDQRL4VPTNPQeV3MgAw/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/3QdLM2p0dDQRL4VPTNPQeV3MgAw/1/da"><img src="http://feedads.g.doubleclick.net/~a/3QdLM2p0dDQRL4VPTNPQeV3MgAw/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/use-linq-and-reflection-to-find-matching-properties/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/use-linq-and-reflection-to-find-matching-properties/</feedburner:origLink></item>
		<item>
		<title>Guidelines and Best Practices in Optimizing LINQ</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/iYol07lz6Ws/</link>
		<comments>http://blog.linqexchange.com/index.php/guidelines-and-best-practices-in-optimizing-linq-performance/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 08:45:35 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[data context]]></category>
		<category><![CDATA[linq to sql]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=138</guid>
		<description><![CDATA[Language Integrated Query (LINQ) is a query execution pipeline for use in the managed environment of .NET Framework. In essence, LINQ is Microsoft&#8217;s object relational mapper between your business objects and the underlying data sources and provides a simplified framework for accessing relational data in an object-oriented fashion. Although LINQ is great in the sense [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Language Integrated Query (LINQ) is a query execution pipeline for use in the managed environment of .NET Framework.  In essence, LINQ is Microsoft&#8217;s object relational mapper between your  business objects and the underlying data sources and provides a simplified  framework for accessing relational data in an object-oriented fashion.</p>
<p>Although LINQ is great in the sense that you can query data in your object model seamlessly, there are certain factors  that you need to consider to ensure that your application performs to the extent  you need it to. This article takes a look at some of the best practices that  you can follow for enhancing the performance of LINQ in your applications.</p>
<p>The Best Practices</p>
<p>Here are some of the best practices that you can follow to boost your LINQ query performance.</p>
<p><strong><em>Object tracking.</em></strong> Turn ObjectTrackingEnabled Property off if not  required. If you need only to read data through the data context and don&#8217;t need to  edit the data, you should turn off ObjectTrackingEnabled property; doing so will  turn off the unnecessary identity management of objects and help boost the application&#8217;s performance.</p>
<p>Here is an example:</p>
<p>using (TestDataContext dataContext = new TestDataContext())</p>
<p>{</p>
<p>dataContext.ObjectTrackingEnabled = false;</p>
<p>}</p>
<p>Data Contexts</p>
<p>If there are multiple disconnected databases that you&#8217;re using in your application, try using multiple data contexts to reduce  the identity management and object tracking overhead costs. You should  attach only those objects to your data context that have been changed.</p>
<p><strong><em>Compiled queries.</em></strong> You can use compiled queries to boost your  application&#8217;s performance. But remember that a compiled query could be costly when used for the  first time. So, do ensure you use compiled queries only in situations where  you need them that is, when you need a query to be used repeatedly.</p>
<p><strong><em>Optimistic concurrency.</em></strong> Concurrency handling is a mechanism that  enables you to detect and resolve conflicts that arise out of concurrent requests to  the same resource at any point in time. Concurrency in ADO.NET is of two types:  optimistic and pessimistic. LINQ follows an optimistic concurrency model by  default. You should avoid using optimistic concurrency if not needed. To turn off the  check for optimistic concurrency, you can use UpdateCheck.Never in the  attribute level mapping for your entity classes, as shown below:</p>
<p>[Column(Storage="_FirstName", DbType="NText",</p>
<p>UpdateCheck=UpdateCheck.Never)]</p>
<p>public string FirstName</p>
<p>{</p>
<p>get</p>
<p>{</p>
<p>return this._FirstName;</p>
<p>}</p>
<p>set</p>
<p>{</p>
<p>if ((this._FirstName != value))</p>
<p>{</p>
<p>this.OnFirstNameChanging(value);</p>
<p>this.SendPropertyChanging();</p>
<p>this._FirstName = value;</p>
<p>this.SendPropertyChanged(&#8220;FirstName&#8221;);</p>
<p>this.OnFirstNameChanged();</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p><strong><em>Retrieve selective data.</em></strong> You should use Take and Skip methods  appropriately when you need to bind paged data to data controls. Here is an example:</p>
<p>private List&lt;Student&gt; GetStudentRecordss(int index, int size)</p>
<p>{</p>
<p>using (TestDataContext dataContext = new TestDataContext())</p>
<p>{</p>
<p>return dataContext.Students</p>
<p>.Take&lt; Student &gt;( size)</p>
<p>.Skip&lt; Student &gt;( index * size)</p>
<p>.ToList&lt; Student&gt;();</p>
<p>}</p>
<p>}</p>
<p>You should also filter down your required data appropriately using DataLoadOptions.AssociateWith so that only the data  that is required is returned. Here is an example that shows how you can use  DataLoadOptions.AssociateWith to retrieve selective data in LINQ:</p>
<p>using (TestDataContext dataContext = new TestDataContext())</p>
<p>{</p>
<p>DataLoadOptions dataLoadOptions = new DataLoadOptions();</p>
<p>dataLoadOptions.AssociateWith&lt;Employee&gt;(emp=&gt; emp.Department.Where&lt;Department&gt;(dept =&gt; dept.DeptCode == 1));</p>
<p>dataContext.LoadOptions = dataLoadOptions;</p>
<p>}</p>
<p><strong><em>Analyze queries.</em></strong> You can also analyze how your LINQ queries have  generated the corresponding SQL statements and monitor them in the Visual Studio IDE.  To do this, you need to use the Log property of the data context as shown in  the code snippet below:</p>
<p>using (TestDataContext dataContext = new TestDataContext())</p>
<p>{</p>
<p>#if DEBUG</p>
<p>dataContext.Log = Console.Out;</p>
<p>#endif</p>
<p>}</p>
<p> </p>
<p>[<a href="http://www.sqlmag.com/article/sql-server/guidelines-and-best-practices-in-optimizing-linq-performance.aspx" target="_blank">SQL Server Magazine</a>]</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/XbSf1MyZmjpyuAEa2O2IePoC3ao/0/da"><img src="http://feedads.g.doubleclick.net/~a/XbSf1MyZmjpyuAEa2O2IePoC3ao/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/XbSf1MyZmjpyuAEa2O2IePoC3ao/1/da"><img src="http://feedads.g.doubleclick.net/~a/XbSf1MyZmjpyuAEa2O2IePoC3ao/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/guidelines-and-best-practices-in-optimizing-linq-performance/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/guidelines-and-best-practices-in-optimizing-linq-performance/</feedburner:origLink></item>
		<item>
		<title>Why You Need to Know LINQ to XML</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/cRxOiSWcgok/</link>
		<comments>http://blog.linqexchange.com/index.php/why-you-need-to-know-linq-to-xml/#comments</comments>
		<pubDate>Wed, 24 Mar 2010 08:51:01 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[linq c#]]></category>
		<category><![CDATA[linq to xml]]></category>
		<category><![CDATA[xelement]]></category>
		<category><![CDATA[xml dom]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=132</guid>
		<description><![CDATA[In .NET 3.5, the primary device for general processing of XML is LINQ To XML. This provides a lightweight, LINQ-friendly DOM along with a set of query operators. In SiIlverlight, this is your only choice &#8211; XmlDocument and related classes are not supported. Even without its LINQ support, the LINQ To XML DOM is valuable [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>In .NET 3.5, the primary device for  general processing of XML is LINQ To XML. This 	 provides a lightweight, LINQ-friendly DOM along with a set of query  operators.</p>
<p>In SiIlverlight, this is your only  choice &#8211; XmlDocument and related classes are not 	 supported. Even without its LINQ support, the LINQ To XML DOM is  valuable as 	 an easy – to – use facade over the XmlReader / Writer classes.</p>
<p>All of the LINQ To XML types are  defined in the <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq%28VS.95%29.aspx">System.Xml.Linq</a> namespace.</p>
<p>The LINQ To XML DOM, or “X-DOM”  consists of types like <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx">XDocument</a>,  <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.aspx">XElement</a>,  and XAttribute. All of the methods are “LINQ – friendly” in that they  emit IEnumerable 	 sequences on which you can query. The constructors are designed so  that you can 	 build an X-DOM tree through a LINQ projection.</p>
<p>For example, this LINQ To SQL query projects directly into an X-DOM:</p>
<p>XElement xml = new XElement(&#8220;contacts&#8221;,<br /> from c in db.Contacts<br /> orderby c.ContactId<br /> select new XElement(&#8220;contact&#8221;,<br /> new XAttribute(&#8220;contactId&#8221;, c.ContactId),<br /> new XElement(&#8220;firstName&#8221;, c.FirstName),<br /> new XElement(&#8220;lastName&#8221;, c.LastName))<br /> );</p>
<p>XElement is the most frequently used  class. XDocument represents the root of an XML 	 tree; it wraps the root XElement with an XDeclaration, processing  instructions,and 	 other root-level items. However, its use is optional – you can load,  manipulate 	 and save an X-DOM without creating an XDocument.</p>
<p>XElement and XDocument offer static  Load and Parse methods. Load builds an X-DOM 	 through a file, URL, TextReader, or an XmlReader. Parse builds an  X-DOM from 	 a string.</p>
<p>Examples:</p>
<p>XDocument fromRss = XDocument.Load(  “http://www.eggheadcafe.com/rss.xml”);<br /> (In SIlverlight, this method only works with relative urls)</p>
<p>XElement fromSettings =  XElement..Load(“C:\MyProject\web.config”);</p>
<p>XElement person = XElement.Parse(  @”&lt;Person&gt; <br /> &lt;FirstName&gt;John&lt;/FirstName&gt; <br /> &lt;LastName&gt;Rogers&lt;/LastName&gt; <br /> &lt;/Person&gt;”);</p>
<p>XNode provides a static ReadFrom  method that can instantiate and populate any type 	 of node from an XmlReader. It stops after reading one complete node so  you can 	 continue to read nodes manually from the XmlReader.</p>
<p>You can also use an XmlReader or  XmlWriter to read and write an XNode via its CreateReader 	 and CreateWriter methods.</p>
<p>If you call ToString on any Node, this  converts its content to an XML string formatted 	 with line breaks and indentation.</p>
<p>XElement and XDocument also have a  Save method that writes an X-DOM to a file, TextWriter 	 or XmlWriter. WIth a file, the declaration is written automatically.  There is 	 also a WriteTo method in XNode that accepts an XmlWriter.</p>
<p>Here is an example of how one might  use a LINQ To XML query to populate a Silverlight 	 ListBox containing a StackPanel, directly from a consumed RSS feed:</p>
<p>namespace  RSS <br /> { <br /> public class RssItem <br /> { <br /> public string Title { get; set; } <br /> public string Description { get; set; } <br /> public string Link { get; set; } <br /> public string PubDate { get; set;} <br /> } <br /> public partial class MainPage : UserControl <br /> { <br /> public MainPage() <br /> { <br /> InitializeComponent(); <br /> WebClient wc = new WebClient(); <br /> wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); <br /> wc.DownloadStringAsync(new Uri(&#8220;http://www.eggheadcafe.com/rss.xml&#8221;)); <br /> }</p>
<p>void  wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) <br /> { <br /> XElement rss= XElement.Parse(e.Result); <br /> var items = from item in rss.Descendants(&#8220;item&#8221;) <br /> select new RssItem() <br /> { <br /> Title = item.Element( &#8220;title&#8221;).Value, <br /> Description = item.Element(&#8220;description&#8221;).Value, <br /> Link =item.Element(&#8220;link&#8221;).Value, <br /> PubDate = item.Element(&#8220;pubDate&#8221;).Value <br /> }; <br /> FeedList.ItemsSource = items.ToList(); <br /> } <br /> } <br /> }</p>
<p>And the XAML:</p>
<p>&lt;UserControl xmlns:data=&#8221;clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data&#8221;  	 x:Class=&#8221;RSS.MainPage&#8221; <br /> xmlns=&#8221;http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221; <br /> xmlns:x=&#8221;http://schemas.microsoft.com/winfx/2006/xaml&#8221; <br /> xmlns:d=&#8221;http://schemas.microsoft.com/expression/blend/2008&#8243; xmlns:mc=&#8221;http://schemas.openxmlformats.org/markup-compatibility/2006&#8243; <br /> mc:Ignorable=&#8221;d&#8221; d:DesignWidth=&#8221;640&#8243; d:DesignHeight=&#8221;480&#8243;&gt; <br /> &lt;Grid x:Name=&#8221;LayoutRoot&#8221;  Width=&#8221;400&#8243;  Height=&#8221;400&#8243;&gt; <br /> &lt;ListBox  x:Name=&#8221;FeedList&#8221; Width=&#8221;400&#8243; Height=&#8221;400&#8243; Visibility=&#8221;Visible&#8221;&gt; <br /> &lt;ListBox.ItemTemplate&gt; <br /> &lt;DataTemplate&gt; <br /> &lt;StackPanel x:Name=&#8221;Stack1&#8243; Orientation=&#8221;Vertical&#8221; Visibility=&#8221;Visible&#8221;&gt; <br /> &lt;HyperlinkButton Width=&#8221;400&#8243; Height=&#8221;24&#8243; FontFamily=&#8221;Arial&#8221; NavigateUri=&#8221;{Binding Link}&#8221; Content=&#8221;{Binding Title}&#8221; /&gt; <br /> &lt;TextBlock Width=&#8221;400&#8243; Height=&#8221;24&#8243; FontFamily=&#8221;Arial&#8221; FontWeight=&#8221;Bold&#8221; Foreground=&#8221;Black&#8221; Text=&#8221;{Binding Description}&#8221; TextWrapping=&#8221;Wrap&#8221;  /&gt; <br /> &lt;TextBlock Width=&#8221;400&#8243; Height=&#8221;24&#8243; FontFamily=&#8221;Arial&#8221; Text=&#8221;{Binding PubDate}&#8221; /&gt; <br /> &lt;/StackPanel&gt; <br /> &lt;/DataTemplate&gt; <br /> &lt;/ListBox.ItemTemplate&gt; <br /> &lt;/ListBox&gt; <br /> &lt;/Grid&gt; <br /> &lt;/UserControl&gt;</p>
<p>Interestingly, the above example will not work with anonymous  types (e.g. select new {  Title =&#8230;. ). You need to define a nominal container  class (RssItem, above) in order 	 for databinding to Silverlight controls to work.</p>
<p>Various LINQ operators can be combined  and chained to provide specific filtering 	 similar to the WHERE, ORDER BY, AND JOIN clauses (among others) in a  SQL query, 	 giving the developer great flexibility once these techniques are  mastered.</p>
<p>Navigation is accomplished through a set of Properties on the XNode  object, such 	 as Parent, AncestorXXX, and others. Intellisense will provide a rich  list of 	 choices to choose from and experiment with; all you need to do is type  a “.” 	 dot after an XElement / XNode variable to see the list.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/n2RG96kNXlNyRlcqBaSrJLHTX9s/0/da"><img src="http://feedads.g.doubleclick.net/~a/n2RG96kNXlNyRlcqBaSrJLHTX9s/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/n2RG96kNXlNyRlcqBaSrJLHTX9s/1/da"><img src="http://feedads.g.doubleclick.net/~a/n2RG96kNXlNyRlcqBaSrJLHTX9s/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/why-you-need-to-know-linq-to-xml/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/why-you-need-to-know-linq-to-xml/</feedburner:origLink></item>
		<item>
		<title>How To Limit String Field Lengths for LINQ to SQL</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/LfRzucqzl7M/</link>
		<comments>http://blog.linqexchange.com/index.php/how-to-limit-string-field-lengths-for-linq-to-sql/#comments</comments>
		<pubDate>Mon, 08 Mar 2010 08:20:51 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=126</guid>
		<description><![CDATA[We recently had an issue where a string value in our LINQ object was changed and became longer than the database field it represented. Whenever we tried to apply the changes to the database we would get an error. Now, I know that the correct solution is to implement the proper checks earlier on in [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>
        We recently had an issue where a string value in our LINQ object was changed<br />
        and became longer than the database field it represented. Whenever we tried<br />
        to apply the changes to the database we would get an error. Now, I know that<br />
        the correct solution is to implement the proper checks earlier on in the change<br />
        cycle but it just erks me a little that the LINQ object doesn’t say:<br />
        &#8220;Hey, you, coder &#8211; you can’t set a value that long to this property because it’s<br />
        too long&#8221;, when it clearly know what it is.
    </p>
<p>
        If you look at the definition of one of the Columns you will see that it has an<br />
        Attribute of type ColumnAttribute. This attribute stores all the information<br />
        required to map the field back to the database.
    </p>
<blockquote><p>
        [Column(Storage="_AColumn", DbType="VarChar(50) NOT NULL", CanBeNull=false)]<br />
        public string AColumn<br />
        {<br />
        &nbsp;&nbsp;get<br />	<br />
        &nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;return this._AColumn;<br />	<br />
        &nbsp;&nbsp;}<br />	<br />
        &nbsp;&nbsp;set<br />	<br />
        &nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;if ((this._AColumn != value))<br />	<br />
        &nbsp;&nbsp;&nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.OnNameChanging(value);<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.SendPropertyChanging();<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this._AColumn = value;<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.SendPropertyChanged(&#8220;AColumn&#8221;);<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;this.OnNameChanged();<br />
        &nbsp;&nbsp;&nbsp;&nbsp;}<br />
        &nbsp;&nbsp;}<br />
        }</p>
</blockquote>
<p>
        We can clearly see from this that our LINQ object does know the column<br />
        length so i decide to write a routine to trim off the excess fat. The<br />
        routine, when we SubmitChanges during OnValidate, uses reflection to get<br />
        the field length and trim the value to fit. Now this could also easily<br />
        be used to notify you of fields that are too long as well.
    </p>
<p>
        To do this we have to extend our LINQ Data Context. The actual DataContext’s<br />
        name is MyDataContext. So we will name the extended one MyDataContext2&#8230;<br />
        creative huh? We then enumerate through the class’ Properties and then each<br />
        Properties Column attributes.
    </p>
<blockquote><p>
        using System;<br />
        using System.Collections.Generic;<br />
        using System.Linq;<br />
        using System.Text;<br />
        using System.Configuration;<br />
        using System.Web;<br />
        using System.Reflection;<br />
        using System.Data.Linq.Mapping;</p>
<p>        public class MyDataContext2 : MyDataContextDataContext<br />
        {<br />
        &nbsp;&nbsp;public MyDataContext2 ()<br />
        &nbsp;&nbsp;: base(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)<br />	<br />
        &nbsp;&nbsp;{<br />
        &nbsp;&nbsp;}<br />
        }</p>
<p>        &nbsp;&nbsp;public partial class MyTable<br />
        &nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;partial void OnValidate(System.Data.Linq.ChangeAction action)<br />
        &nbsp;&nbsp;&nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Trim all the string fields so that we don&#8217;t get DB errors.</p>
<p>        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Check each property in the table<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;foreach (MemberInfo memInfo in (typeof(MyTable)).GetProperties())<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Only Loop through Column attributes<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;foreach (object attribute in memInfo.GetCustomAttributes(typeof(ColumnAttribute), true))<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ColumnAttribute ca = (ColumnAttribute)attribute;<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PropertyInfo propInfo = (PropertyInfo)memInfo;</p>
<p>        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//Only limit varchar values<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (ca.DbType.ToLower().Contains(&#8220;varchar&#8221;))<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;string dbType = ca.DbType.ToLower();<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;string varchar = &#8220;varchar(&#8220;;<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int noStart = dbType.ToLower().IndexOf(varchar) + varchar.Length;<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int noEnd = dbType.IndexOf(&#8220;)&#8221;, noStart);</p>
<p>        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;string sLength = dbType.Substring(noStart, noEnd &#8211; noStart); //strings are stored as VarChar(XXX) NOT NULL</p>
<p>        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int iLength = 0;<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int.TryParse(sLength, out iLength);</p>
<p>        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;string value = string.Empty;</p>
<p>        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (propInfo.GetValue(this, null) != null)<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value = propInfo.GetValue(this, null).ToString();</p>
<p>        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (value.Length &gt; iLength)<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;propInfo.SetValue(this, value.Substring(0, iLength), null);<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
        &nbsp;&nbsp;&nbsp;&nbsp;}<br />
        &nbsp;&nbsp;}<br />
        }</p>
</blockquote>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/5brklfkGdoxGJrQf9plXf3pXZzs/0/da"><img src="http://feedads.g.doubleclick.net/~a/5brklfkGdoxGJrQf9plXf3pXZzs/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/5brklfkGdoxGJrQf9plXf3pXZzs/1/da"><img src="http://feedads.g.doubleclick.net/~a/5brklfkGdoxGJrQf9plXf3pXZzs/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/how-to-limit-string-field-lengths-for-linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/how-to-limit-string-field-lengths-for-linq-to-sql/</feedburner:origLink></item>
		<item>
		<title>Generic Delegates and Lambda Expressions</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/a7FrtVi9jzs/</link>
		<comments>http://blog.linqexchange.com/index.php/understanding-generic-delegates-and-lambda-expressions/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 12:14:58 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[call for content]]></category>
		<category><![CDATA[delegates]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[lambda expressions]]></category>
		<category><![CDATA[linq c#]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=121</guid>
		<description><![CDATA[Generic delegates and lambda expressions underpin LINQ. If you’ve been struggling to get your arms around these new concepts, this post should help demystify matters for you. Of course, there are a a host of other new .NET language features that enable LINQ as well. These include extension methods, type inference, anonymous types, object initializers, [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Generic delegates and lambda expressions underpin LINQ. If you’ve been  struggling to get your arms around these new concepts, this post should help  demystify matters for you.</p>
<p>Of course, there are a a host of other new .NET language features that enable  LINQ as well. These include extension methods, type inference, anonymous types,  object initializers, and custom iterators, just to name a few! In this post,  I’ll address generic delegates and lambda expressions as they pertain to LINQ  (that is, as they pertain to the extension methods provided in .NET 3.5 to  support LINQ), and I’ll cover some of the other new language features in future  posts.</p>
<h3>LINQ Query Syntax</h3>
<p>There is simply no LINQ without generic delegates and lambda expressions, yet  it would <em>seem </em>at first that you can write simple LINQ queries without  seeing or touching either a generic delegate or a lambda expression. Here’s a  simple example that queries from a collection of customers in <em>custs</em>. In  the <em>where </em>clause, we use a boolean <em>allCustomers</em> variable to  control whether all customers or only USA customers will be returned.</p>
<blockquote><p>var allCustomers = false;</p>
<p>var q =<br /> from c in custs<br /> where c.Country == &#8220;USA&#8221; || allCustomers == true<br /> orderby c.FirstName<br /> select c;</p>
</blockquote>
<p>Where’s the generic delegate and the lambda expression in this LINQ query? Oh  they’re there all right, but the <em>LINQ query syntax </em>hides those details  from the code.</p>
<h3>LINQ Method Call Syntax</h3>
<p>In reality, the compiler (C# in this case, but VB .NET as well) is supporting  a sugar-coated syntax that is strikingly similar to an ordinary SQL query in the  RDBMS world, but which <em>really</em> amounts to a <em>chained set of method  calls</em>.</p>
<p>What this means is that there is really no such thing as a <em>where</em> clause in LINQ–it’s a <em>Where </em>extension method call.</p>
<p>And guess what? There’s no such thing as an <em>orderby</em> clause  either–it’s an <em>OrderBy </em>extension method call, chained to the end of the  <em>Where</em> method call.</p>
<p>Meaning that the previous query is treated by the compiler exactly as if you  had coded it using <em>LINQ method call syntax</em> as follows:</p>
<blockquote><p>var q = custs<br /> .Where(c =&gt; c.Country == &#8220;USA&#8221; || allCustomers == true)<br /> .OrderBy(c =&gt; c.FirstName);</p>
</blockquote>
<p>So this code looks more “conventional,” eh? We’re invoking the <em>Where </em>method on the collection of customers, and then invoking the <em>OrderBy </em>method on the result returned by <em>Where</em>, and obtaining our final  filtered and sorted results in <em>q</em>.</p>
<blockquote><p><em>LINQ query syntax is obviously cleaner than LINQ method call syntax,    but it’s important to understand that only LINQ method call syntax fully    implements the complete set of LINQ Standard Query Operators (SQOs), so that    you will sometimes be forced to use method call syntax. Also realize that it’s    common and normal to use combinations of the two in a single query (I’ll show    examples of this using .Concat and other methods in future  posts).</em></p>
</blockquote>
<p>Two questions arise at this point:</p>
<p>1) How did the customer collection, which is a <em>List&lt;Customer&gt; </em>in our example, get a <em>Where </em>and <em>OrderBy </em>method?</p>
<p>2) What is the =&gt; operator in the method parameters, and what does it do  (and how the heck do you pronounce it)?</p>
<p>The answer to the first question is simple: Extension methods. I’ll cover  those in more detail in a future post, but for now just understand that the .NET  framework 3.5 “extends” any class that implements <em>IEnumerable&lt;T&gt; </em>(virtually any collection, such as our <em>List&lt;Customer&gt;)</em> with  the <em>Where </em>and <em>OrderBy </em>methods, as well as many other methods  that enable LINQ.</p>
<h3>Generic Delegates</h3>
<p>The second question is much juicier. First, the =&gt; is the <em>lambda  operator</em>, and many people verbalize it as <em>‘goes to’</em>. So <em>‘c  =&gt; …’</em> is read aloud as <em>‘c goes to…’</em></p>
<p>To understand lambdas, you need to understand <em>generic delegates </em>and <em>anonymous methods.</em> And to best understand those is to  review <em>delegates </em>and <em>generics </em>themselves. If you’ve been  programming .NET for any length of time, you’re certain to have encountered  delegates. And as of .NET 2.0 (VS 2005), generics have been an important  language feature for OOP as well.</p>
<p>A <em>delegate </em>is a data type that defines the “shape” (signature) of a  method call. Once you have defined a delegate, you can declare a variable as  that delegate. At runtime, the variable can then be pointed to (and then invoke)  any available method that matches the signature defined by the delegate.  <em>EventHandler </em>is a typical example of a delegate defined by the  .NET framework. Here is how .NET defines the <em>EventHandler </em>delegate:</p>
<blockquote><p>public delegate void EventHandler(object sender, EventArgs e);</p>
</blockquote>
<p>This delegate is suitable for pointing to any method that returns no value  (<em>void</em>), and accepts two parameters (<em>object sender </em>and  <em>EventArgs e</em>); in other words, a typical event handler that has no  special event arguments to be passed.</p>
<p>A generic delegate is nothing more than an ordinary delegate, but supports  generic type declarations for achieving strongly-typed definitions of the  delegate at compile time. This is the same way generics are used for  classes. For example, just as the framework provides  a <em>List&lt;T&gt;</em> class so that you can have a List <em>of  anything</em>, it now also provides a small set of generic delegates named  <em>Func</em> that can be used to stongly type many different method signatures;  essentially, any method that takes from zero to 4 parameters of <em>any </em>type (<em>T1</em> through <em>T4</em>) and returns an object of <em>any </em>type (<em>TResult</em>):</p>
<blockquote><p>public delegate TResult Func&lt;TResult&gt;();<br />public delegate TResult Func&lt;T, TResult&gt;(T arg);<br />public delegate TResult Func&lt;T1, T2, TResult&gt;(T1 arg1, T2 arg2);<br />public delegate TResult Func&lt;T1, T2, T3, TResult&gt;(T1 arg1, T2 arg2, T3 arg3);<br />public delegate TResult Func&lt;T1, T2, T3, T4, TResult&gt;(T1 arg1, T2 arg2, T3 arg3, T4 arg4);</p>
</blockquote>
<p>Delegates as Parameters</p>
<p>With these generic <em>Func</em> delegates baked into the .NET  framework, LINQ queries can use them as parameters to extension methods such as  <em>Where </em>and <em>OrderBy</em>. Let’s examine one overload of the <em>Where </em>extension method:</p>
<blockquote><p>public static IEnumerable&lt;TSource&gt; Where&lt;TSource&gt;(<br /> this IEnumerable&lt;TSource&gt; source,<br /> Func&lt;TSource, bool&gt; predicate);</p>
</blockquote>
<p>What does this mean? Let’s break it down. And to better suit our  particular example and simplify the explanation, let’s substitute <em>Customer </em>for <em>TSource</em>:</p>
<p>1) It’s a method called <em>Where&lt;Customer&gt;.</em></p>
<p>2) It returns an <em>IEnumerable&lt;Customer&gt;</em> sequence.</p>
<p>3) It’s an extension method available to operate on any  <em>IEnumerable&lt;Customer&gt;</em>instance (as denoted by the special  <em>this</em> keyword in the signature), such as the  <em>List&lt;Customer&gt;</em> in our example. The <em>this </em>keyword used in  this context means that an extension method for the type following the <em>this </em>keyword is being defined, rather than definining what looks like the first  parameter to the method.</p>
<p>4) It takes a single <em>predicate </em>parameter of type  <em>Func&lt;Customer, bool&gt;.</em></p>
<p>Number 4 is key. <em>Func&lt;Customer, bool&gt; </em>is the second <em>Func </em>generic delegate shown above, <em>Func&lt;T, TResult&gt;</em>, where <em>T </em>is <em>Customer </em>and <em>TResult </em>is <em>bool </em>(Boolean). The <em>Func&lt;Customer, bool&gt; </em>delegate  refers to any method that accepts a <em>Customer </em>object and returns a  <em>bool </em>result.  This means that the <em>Where&lt;Customer&gt; </em>method takes a delegate (function pointer) that points to <em>another</em> method which actually implements the filtering logic. This <em>other </em>method  will receive each <em>Customer </em>object as the LINQ query iterates the source  sequence <em>List&lt;Customer&gt;</em>, apply the desired filtering  criteria on it, and return a true or false result in the <em>bool</em> return value that controls whether this particular <em>Customer </em>object  should be selected by the query.</p>
<p>How does all that get expressed simply with: <em>.Where(c =&gt; c.Country ==  “USA” || allCustomers == true)</em>?</p>
<p>The best way to answer that question is to first demonstrate two other ways  of invoking the <em>Where </em>method. The first is to explicitly provide a  delegate instance of <em>Func&lt;Customer, bool&gt;</em> that points to another  method called <em>IsCustomerCountryUSA</em>:</p>
<blockquote><p>private void MainMethod()<br />{<br /> var filterMethod = new Func&lt;Customer, bool&gt;(IsCustomerCountryUSA);<br /> var q = custs.Where(filterMethod);<br />}</p>
<p>private bool IsCustomerCountryUSA(Customer c)<br />{<br /> return (c.Country == &#8220;USA&#8221;);<br />}</p>
</blockquote>
<p>The <em>Where </em>method takes a single parameter, which is a new instance  of the <em>Func&lt;TSource, T&gt;</em> generic delegate that points to a method  named <em>IsCustomerCountryUSA</em>. This works because <em>IsCustomerCountryUSA </em>accepts a <em>Customer </em>object and returns a <em>bool </em>result,  which is the signature defined by <em>Func&lt;Customer, bool&gt;</em> expected  as a parameter by <em>Where&lt;Customer&gt;</em>.  Inside the  <em>IsCustomerCountryUSA</em>, filtering logic is applied. Note that because we  have created <em>IsCustomerCountryUSA </em>as a completely separate method, it  cannot access the <em>allCustomers </em>variable defined locally in the  calling method (the variable that controls whether all or only USA customers  should be selected, as shown at the beginning of this post). Furthermore,  because the signature of the <em>IsCustomerCountryUSA </em>method is fixed  as determined by <em>Func&lt;Customer, bool&gt;</em>, we can’t just pass  the <em>allCustomers </em>variable along as another parameter either.   Thus, this approach would require you to define the <em>allCustomers </em>variable as a private member if you wanted to include it in the filtering  logic of the <em>IsCustomerCountryUSA </em>method.</p>
<h3>Anonymous Methods</h3>
<p>Anonymous methods were introduced at the same time as generics in .NET 2.0  (VS 2005). They are useful in cases such as this, where the method we’re  creating for the delegate only needs to be called from one place, so the entire  method body is simply coded in-line. Since it’s coded in-line at the one and  only place it’s invoked, the method doesn’t need to be given a name, hence the  term <em>anonymous method</em>.</p>
<p>To refactor the delegate instance version of the code to use an  anonymous method, replace the <em>Func </em>parameter passed to the  <em>Where </em>method with the actual method signature and body as follows:</p>
<blockquote><p>var q = custs.Where(delegate(Customer c) { return c.Country == &#8220;USA&#8221; || allCustomers == true; });</p>
</blockquote>
<p>The keyword <em>delegate </em>indicates you’re pointing the delegate  parameter <em>Func&lt;Customer, bool&gt;</em> expected by the <em>Where </em>method to an anonymous method. The anonymous method isn’t named, as  mentioned, but it must match the <em>Func&lt;Customer, bool&gt; </em>signature,  meaning it must accept a <em>Customer </em>object parameter and return a  <em>bool </em>result. The explicit signature following the <em>delegate </em>keyword defines the expected single <em>Customer </em>object parameter, and  the expected <em>bool </em>result is inferred from the fact that the method  returns an expression that resolves to a <em>bool </em>value. If the anonymous  method used any other signature or returned anything other than a <em>bool </em>result, the compiler would fail to build your code  because the  <em>Where&lt;Customer&gt; </em>method is defined to accept only a  <em>Func&lt;Customer, bool&gt;</em> delegate.</p>
<p>So now the method body containing the filtering logic that was formerly coded  in the separate <em>IsCustomerCountryUSA </em>method appears in braces  right after the anonymous method signature. But there’s another huge advantage  here besides saving the overhead of declaring a separate method for the  filtering logic. Because anonymous methods appear inside of the method that  calls them, they magically gain access to the local variables of the calling  method. Thus, this implementation can also test the <em>allCustomers </em>variable, even though it’s defined in the calling method which would  normally be inaccessible to the method being called. Because of this feature,  the <em>allCustomers </em>variable defined as a local variable in the  calling method can be tested by the anonymous method as part of the filtering  criteria. That means it’s not necessary to define private fields to share local  variables defined in a method with an anonymous method that the method  calls, as demonstrated here). The result is less code, and cleaner code (though  you should be aware that the compiler pulls some fancy tricks to make this  possible, and there is a degree of additional runtime overhead involved when  accessing local variables of the calling method from the anonymous method being  called).</p>
<h3>Lambda Expressions</h3>
<p><em>Lambdas </em>were introduced in .NET 3.5 (VS 2008) as a more elegant way  of implementing anonymous methods, particularly with LINQ. When a lambda is used  to represent an anonymous method containing a single expression which returns a  single result, that anonymous method is called a <em>lambda expression</em>.  Let’s first refactor our query by converting it from an anonymous method to a  lambda:</p>
<blockquote><p>var q = custs.Where((Customer c) =&gt; { return c.Country == &#8220;USA&#8221; || allCustomers == true; });</p>
</blockquote>
<p>All we did was drop the delegate keyword and add the =&gt; (“goes to”)  operator. The rest looks and works the same as before.</p>
<p>This lambda consists of a single expression that returns a single result,  which qualifies it to be refactored as a lambda <em>expression</em> like  this:</p>
<blockquote><p>var q = custs.Where(c =&gt; c.Country == &#8220;USA&#8221; || allCustomers == true);</p>
</blockquote>
<p>This final version again works exactly the same way, but has become very  terse. First, the <em>Customer </em>data type in the signature isn’t needed,  since it’s inferred as the <em>TSource </em>in <em>Func&lt;TSource,  bool&gt;</em>. The parentheses surrounding the signature are also not needed, so  they’re dropped too. Secondly, since lambda expressions by definition consist of  only a single statement, the opening and closing braces for the method body  aren’t needed and also get dropped. Finally, since lambda expressions by  definition return a single result, the <em>return </em>keyword isn’t needed and  is also dropped.</p>
<p>Besides offering an even terser syntax, lambda expressions provide two  important additional benefits over anonymous methods. First, as just  demonstrated, the data type of the parameter in the signature needn’t be  specified since it’s inferred automatically by the compiler. That means that  <em>anonymous types </em>(such as those often created by projections defined in  the <em>select </em>clause of a LINQ query) can also be passed to lambda  expressions. Anonymous types cannot be passed to any other type of method, so  this capability was absolutely required to support anonymous types with LINQ.  Second, lambda expressions can be used to build expression trees at runtime,  which essentially means that your query <em>code</em> gets converted into query  <em>data</em> which can then be processed by a particular LINQ  implementation at runtime. For example, LINQ to SQL builds an expression tree  from the lambda expressions in your query, and generates the appropriate T-SQL  for querying SQL Server from the expression tree. Future posts will cover  anonymous types and expression trees in greater detail.</p>
<h3>To Sum It All Up</h3>
<p>So this final lambda expression version invokes the <em>Where</em> method  on the <em>List&lt;Customer&gt;</em> collection in <em>custs</em>. Because  <em>List&lt;Customer&gt; </em>implements <em>IEnumerable&lt;T&gt;</em>, the  <em>Where </em>extension method which is defined for any  <em>IEnumerable&lt;T&gt; </em>is available to be invoked on it. The  <em>Where&lt;Customer&gt; </em>method expects a single parameter of the generic  delegate type <em>Func&lt;Customer, bool&gt;</em>. Such a parameter can be  satisfied by the in-line lambda expression shown above, which accepts a  <em>Customer</em> object as <em>c =&gt;</em>, and returns a <em>bool </em>result  by applying a filtering condition on the customer’s <em>Country </em>property and the calling method’s <em>allCustomers </em>variable.</p>
<p>And as expained at the beginning of this post, the method syntax query using  our final lambda expression is exactly what the compiler would generate for us  if we expressed it using this query syntax:</p>
<blockquote><p>var q =<br /> from c in custs<br /> where c.Country == &#8220;USA&#8221; || allCustomers == true<br /> select c;</p>
</blockquote>
<p>I hope this helps clear up any confusion there is surrounding lambda  expressions in .NET 3.5.</p>
<p>Happy coding!</p>
<p> </p>
<p>This article was submitted by <a href="http://lennilobel.wordpress.com/" target="_blank">Lenni Lobel on .NET and SQL Server Development<br /></a></p>
<p><a href="http://lennilobel.wordpress.com/" target="_blank"><img src="http://0.gravatar.com/avatar/c4a98541a4d07299b0d4fc4d23ca3009?s=64&amp;d=identicon&amp;r=G" alt="Lenni Lobel" title="Generic Delegates and Lambda Expressions" /> </a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/ods2tY3WCsu5OZzQt0JiwKmNmwo/0/da"><img src="http://feedads.g.doubleclick.net/~a/ods2tY3WCsu5OZzQt0JiwKmNmwo/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ods2tY3WCsu5OZzQt0JiwKmNmwo/1/da"><img src="http://feedads.g.doubleclick.net/~a/ods2tY3WCsu5OZzQt0JiwKmNmwo/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/understanding-generic-delegates-and-lambda-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/understanding-generic-delegates-and-lambda-expressions/</feedburner:origLink></item>
		<item>
		<title>Call for LINQ Content</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/_Oi12cHOS08/</link>
		<comments>http://blog.linqexchange.com/index.php/call-for-linq-content/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 08:13:46 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[call for content]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=117</guid>
		<description><![CDATA[As part of our goal to make Linq Exchange a more social website, I&#8217;m inviting you, the friendly reader, to submit your LINQ or Lambda Expression article. Your article will appear on the Linq Exchange website within one week of submission (pending review and approval). You may include one link back to your blog or [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>As part of our goal to make Linq Exchange a more social website, I&#8217;m inviting you, the friendly reader, to submit your LINQ or Lambda Expression article. Your article will appear on the Linq Exchange website within one week of submission (pending review and approval).</p>
<p>You may include one link back to your blog or website (including graphic logo).</p>
<p>Submission Rules:</p>
<ol>
<li>Your article must be about LINQ or Lambda Expressions</li>
<li>Your article must be at least 350 words in length</li>
<li>You must include at least one code example</li>
<li>You may provide one link and graphic logo to your website or blog. This link will be placed at the end of your article.</li>
<li>You may submit your article as a PDF, Word doc, HTML file, or plain text (HTML is preferred, please).</li>
<li>Your article will appear on the Linq Exchange website withing seven days of submission, pending review and approval by the Linq Exchange team.</li>
</ol>
<p> </p>
<p>Submit your articles to <a href="mailto:articles@linqexchange.com">articles@linqexchange.com</a></p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/I2DGG4xXCEGxHZRkhttV5ifN4dI/0/da"><img src="http://feedads.g.doubleclick.net/~a/I2DGG4xXCEGxHZRkhttV5ifN4dI/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/I2DGG4xXCEGxHZRkhttV5ifN4dI/1/da"><img src="http://feedads.g.doubleclick.net/~a/I2DGG4xXCEGxHZRkhttV5ifN4dI/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/call-for-linq-content/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/call-for-linq-content/</feedburner:origLink></item>
		<item>
		<title>Practical Understanding of Lambda Expressions in LINQ</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/soqSipUfMUQ/</link>
		<comments>http://blog.linqexchange.com/index.php/practical-understanding-of-lambda-expressions-in-linq/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 08:10:41 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[expressions]]></category>
		<category><![CDATA[lambda]]></category>
		<category><![CDATA[lambda expressions]]></category>
		<category><![CDATA[linq c#]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=112</guid>
		<description><![CDATA[Lambda expressions are a powerful tool to writing quick, concise code. They can be used in numerous situations, most notably in conjuction with LINQ statements. A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types. All lambda expressions use the lambda [...]


No related posts.

Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">Lambda expressions</a> are a powerful tool to writing quick, concise code. They can be used in numerous situations, most notably in conjuction with LINQ statements.</p>
<p>A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.</p>
<p>All lambda expressions use the lambda operator =&gt;, which is read as &#8220;goes to&#8221;. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x =&gt; y * z is read &#8220;x goes to y times z.&#8221;</p>
<p>Here’s how a typical LINQ query looks like without using lambda expressions:</p>
<blockquote><p>var query = from m in db.PersonalMessages<br /> where m.ConversationID_FK == ConversationID<br /> select m;</p>
</blockquote>
<p>Okay, not bad. It looks like a SQL query in reverse (i.e. you start off with “from” and end with “select”). This is so that intellisense can help you out—if you started with select, it would have on idea where you were going with the query.</p>
<p>we are selecting PersonalMessages where the ConversationID is equal to some value passed into the method. The query itself is kinda verbose, and I like to keep my code short and sweet, so how do I re-write this using lambda expressions? Here is the code, and then we’ll break it down:</p>
<blockquote><p>var query = db.PersonalMessages<br /> .Where(m =&gt; m.ConversationID_FK == ConversationID);</p>
</blockquote>
<p>We got rid of “select&#8217;”, “from” and “in”, etc. Cleaned it up quite a bit. What all is happening though? Basically it’s written out like:</p>
<p>My Query = Get Personal Messages from my data context Where the ConversationID is equal to this #</p>
<p>In other words, it reads exactly like it does in the first written out query, but it’s done faster. The where statement is like a mini-method. You’re defining some variable M (you can use any letter, I always use m for the sake of convention in my code) and then in this case you’re giving m some condition to work with.</p>
<p>You’re basically saying, define m real quick (m=&gt;) as a stand-in for PersonalMessage. Then only return PersonalMessages where m’s ConversationID is equal to some value. Again, just to drill in the point, it’s like typing in:</p>
<blockquote><p>var query = DataContext.PersonalMessages.Where(PersonalMessage=&gt;PresonalMessage.ConvoID = ConvoID);</p>
</blockquote>
<p>Now I want to get even faster with my method calling. Instead of defining a query, then returning it, or doing other things to it, I can easily chain things to it. Lets say I want to return a List of personal messages. I can now do:</p>
<blockquote><p>List&lt;PersonalMessage&gt; myPersonalMessages = db.PersonalMessages<br /> .Where(m =&gt; m.ConversationID_FK == ConversationID)<br /> .ToList();</p>
</blockquote>
<p>Very easy. I can go even further, now, all with the ease of dot notation. Lets say I want to order it by the date the personal message was created. No problem, I can throw in an .OrderBy:</p>
<blockquote><p>List&lt;PersonalMessage&gt; myPersonalMessages = db.PersonalMessages<br /> .Where(m =&gt; m.ConversationID_FK == ConversationID)<br /> .OrderBy(m=&gt;m.DateCreated)<br /> .ToList();</p>
</blockquote>
<p>Again, I’m creating a little “mini-method” that is passing in the personal message as m, and saying to order it by the date it was created. The possibilities are limitless!</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>

<p>No related posts.</p>
<p>Related posts brought to you by <a href='http://mitcho.com/code/yarpp/'>Yet Another Related Posts Plugin</a>.</p>
<p><a href="http://feedads.g.doubleclick.net/~a/LF7fbf1Z8DJzztXC32hYADMxIT4/0/da"><img src="http://feedads.g.doubleclick.net/~a/LF7fbf1Z8DJzztXC32hYADMxIT4/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/LF7fbf1Z8DJzztXC32hYADMxIT4/1/da"><img src="http://feedads.g.doubleclick.net/~a/LF7fbf1Z8DJzztXC32hYADMxIT4/1/di" border="0" ismap="true"></img></a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/practical-understanding-of-lambda-expressions-in-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/practical-understanding-of-lambda-expressions-in-linq/</feedburner:origLink></item>
	</channel>
</rss>
