<?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>Tue, 23 Nov 2010 08:53:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</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>Why LINQ is Better than ForEach</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/kUWJbs_kuK4/</link>
		<comments>http://blog.linqexchange.com/index.php/why-linq-is-better-than-foreach/#comments</comments>
		<pubDate>Tue, 23 Nov 2010 08:53:09 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[foreach]]></category>
		<category><![CDATA[linq c#]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=189</guid>
		<description><![CDATA[I had a discussion today with a software architect who disagreed with me that LINQ to Objects should be used instead of foreach loops. My claim is that LINQ is better. He says that I shouldn’t make such a blanket statement, because LINQ is inefficient. I stand by my assertion. Declarative Code is Easier to [...]
No related posts.

Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<div>
<p>I had a discussion today with a software architect  who disagreed with me that LINQ to Objects should be used instead of  foreach loops. My claim is that LINQ is better. He says that I shouldn’t  make such a blanket statement, because LINQ is inefficient. I stand by  my assertion.</p>
<h2>Declarative Code is Easier to Read</h2>
<p>From  the initial development point of view, writing what you’re doing rather  than how you’re doing it is more succinct, easier to read, and easier  for others to maintain. Even if you don’t know LINQ, which is easier to  decipher?</p>
<pre>var developerNames = employees.Where(e =&gt; e.Role == Role.Developer)                              .OrderBy(e =&gt; e.LastName)                              .Select(e =&gt; e.FullName)                              .ToArray();</pre>
<p>or the 2.0 List&lt;T&gt; way</p>
<pre>public class EmployeeLastNameComparer : IComparer&lt;Employee&gt;{    public int Compare(Employee x, Employee y)    {        return x.LastName.CompareTo(y.LastName);    }}</pre>
<p>…</p>
<pre>var employeeList = new List&lt;Employee&gt;();employeeList.AddRange(employees);employeeList.Sort(new EmployeeLastNameComparer());var names = new List&lt;string&gt;();

foreach (var employee in employeeList){    if (employee.Role == Role.Developer)    {        names.Add(employee.FullName);    }}

var developerNames = names.ToArray();</pre>
<p>I much prefer to read a declarative code than iterative code. But the  architect’s concern about performance is still valid. Let’s check the  numbers. Using <a href="http://www.kodefuguru.com/post/2010/05/03/Generate-Matches-for-Regular-Expressions-Using-Rex.aspx">Rex</a>, I will create an employees array with a thousand members.</p>
<pre>string regexName = @"^[A-Z][a-z]+$";RexSettings nameSettings = new RexSettings(regexName) {     k = 1000,     encoding = CharacterEncoding.ASCII };

var firstNames = RexEngine.GenerateMembers(nameSettings);var lastNames = RexEngine.GenerateMembers(nameSettings);Random randomRole = new Random();            var employees = firstNames.Zip(lastNames,                 (f, l) =&gt; new Employee                             {                                 FirstName = f,                                 LastName = l,                                 Role = (Role)randomRole.Next(3)                             })                .ToArray();</pre>
<p>I then timed both versions of the code using a StopWatch instance. Here are the results for the List&lt;T&gt; version.</p>
<p>00:00:00.0027104   <br />00:00:00.0026925    <br />00:00:00.0028171    <br />00:00:00.0027148    <br />00:00:00.0027858</p>
<p>And now the LINQ version.</p>
<p>00:00:00.0019929   <br />00:00:00.0019156    <br />00:00:00.0019871    <br />00:00:00.0018066    <br />00:00:00.0019116</p>
<p>Okay, clearly the LINQ version is optimized because the filter is  occurring before the sort. It’s time to make the iterative code even  uglier to squeeze some performance out of it (and remember, the LINQ  version is functionally complete and rather clean).</p>
<pre>var employeeList = new List&lt;Employee&gt;();

foreach (var employee in employees){    if (employee.Role == Role.Developer)    {        employeeList.Add(employee) ;    }}

employeeList.Sort(new EmployeeLastNameComparer());var names = new List&lt;string&gt;();

foreach (var employee in employeeList){    names.Add(employee.FullName);}

var developerNames = names.ToArray();</pre>
<p>Now that I’ve optimized the code, the results are much better.</p>
<p>00:00:00.0014110   <br />00:00:00.0013445    <br />00:00:00.0013484    <br />00:00:00.0016516    <br />00:00:00.0013563</p>
<p>Is it really worth that mess to squeeze out a little bit of time? It  really depends on your application. But as you’ll see, that’s still not  an excuse. Besides, if you really cared so much about performance, you  would use arrays and write your own, optimized sort methods. If you must  write those applications, you’re probably using C on an embedded device  and this posting is moot. For business applications, readability trumps  premature optimization.</p>
<h2>Take Advantage of the Hardware</h2>
<p>It’s much easier to take advantage of multiple cores so present in  today’s computers using LINQ. On .NET 4 (or using the Parallel  Extensions with 3.5), it is as simple as adding an extension method or  two.</p>
<pre>var developerNames = employees.AsParallel().AsOrdered()                              .Where(e =&gt; e.Role == Role.Developer)                              .OrderBy(e =&gt; e.LastName)                              .Select(e =&gt; e.FullName)                              .ToArray();</pre>
<p>Again, I must warn against premature optimization. Due to the speed  of the original statement, the overheard is not worth the cost. It will  actually make the routine slower. However, if I add a Thread.Sleep(10)  to the getter of Employee.FullName, the difference is 5 seconds without  The AsParallel() option to 2.5 seconds with it. Needless to say,  optimizing the ForEach version to take advantage of the hardware isn’t  as elegant. Maintaining order requires using a specific overload of  Parallel.ForEach. This situation is easy since we can use an array, but  do not doubt that it requires much work in many situations. Here is the  piece for the code that needs to be optimized.</p>
<pre>string[] names = new string[employeeList.Count];            

Parallel.ForEach(employeeList, (employee, loopState, elementIndex) =&gt;{    names[elementIndex] = employee.FullName;});</pre>
<h2>What If LINQ Really Doesn’t Work In My Situation?</h2>
<p>The important thing isn’t whether or not you use LINQ, the important  thing is to have readable code. Stating what you’re doing is more  maintainable than how you’re doing it. Encapsulation is key. I feel it’s  best to start with the LINQ statement, then optimize if necessary. Here  are the steps to to squeeze out the milliseconds by going from the LINQ  version of the code above to the iterative version while hiding the  complexity, thereby maintaining readability.</p>
<p>The first thing that should be done is to use the <a href="http://www.kodefuguru.com/post/2010/02/12/Reduce-Chain-and-Extract-Projection-Refactorings.aspx">reduce chain refactoring</a>.</p>
<pre>public static class EnumerableEmployee{    public static IEnumerable&lt;string&gt; DeveloperNames(this IEnumerable&lt;Employee&gt; employees)    {        return employees.Where(e =&gt; e.Role == Role.Developer)                        .OrderBy(e =&gt; e.LastName)                        .Select(e =&gt; e.FullName);    }}</pre>
<p>Then call the method with the following.</p>
<pre>var developerNames = employees.DeveloperNames().ToArray();</pre>
<p>Of course, with a name like that, why do you even need a variable? I  love taking a piece of code and making it express the essence of what it  is.</p>
<p>Since the implementation for DeveloperNames() is encapsulated in the  extension method, it’s a simple matter to change that implementation for  the iterative version of the code we were using earlier.</p>
<pre>public static class EnumerableEmployee{    public static IEnumerable&lt;string&gt; DeveloperNames(this IEnumerable&lt;Employee&gt; employees)    {        var employeeList = new List&lt;Employee&gt;();

        foreach (var employee in employees)        {            if (employee.Role == Role.Developer)            {                employeeList.Add(employee);            }        }

        employeeList.Sort(new EmployeeLastNameComparer());        var names = new List&lt;string&gt;();

        foreach (var employee in employeeList)        {            names.Add(employee.FullName);        }

        return names;    }}</pre>
<h2>Conclusion</h2>
<p>The vast majority of code I come across that either can be written in  LINQ or refactored to LINQ has no noticeable, negative performance  impact, but it has a positive impact on maintainability. On top of that,  LINQ statements can be made to scale with the hardware easier, and a  more readable manner, than a collection of iterative statements. LINQ  statements should still be refactored for even further readability, and  by encapsulating the implementation it can be replaced with iterative  code while hiding said code’s complexity.</p>
</div>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fwhy-linq-is-better-than-foreach%2F&amp;title=Why%20LINQ%20is%20Better%20than%20ForEach" id="wpa2a_2"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 Why LINQ is Better than ForEach"  title="Why LINQ is Better than ForEach" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/why-linq-is-better-than-foreach/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/why-linq-is-better-than-foreach/</feedburner:origLink></item>
		<item>
		<title>How to Use Let in LINQ Extension Methods</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/mGvS4Wthb4U/</link>
		<comments>http://blog.linqexchange.com/index.php/how-to-use-let-in-linq-extension-methods/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 08:56:06 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[linq c#]]></category>
		<category><![CDATA[LINQ Extension Methods]]></category>
		<category><![CDATA[LINQ Let]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=184</guid>
		<description><![CDATA[For a variety of reasons (many of which Scott Allen discusses in his wonderful LINQ course), I prefer to use extension method syntax with LINQ instead of query expression syntax. But one thing I miss is the “let” operation that allows me to compute intermediate results and store them in a new variable. This morning [...]
No related posts.

Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>For a variety of reasons (many of which <a href="http://www.pluralsight.com/main/instructor.aspx?name=scott-allen" target="_blank">Scott Allen</a> discusses in his <a href="http://www.pluralsight.com/main/olt/Course.aspx?n=linq-fundamentals" target="_blank">wonderful LINQ course</a>),  I prefer to use extension method syntax with LINQ instead of query  expression syntax. But one thing I miss is the “let” operation that  allows me to compute intermediate results and store them in a new  variable.</p>
<p>This morning I came across a case where this would  really simplify things, so I sat down to remember how to do it (I know  I’ve done it before but I couldn’t remember the trick). So I wrote the  simplest query I could think of using LET…</p>
<pre>string[] input = { "asdf", "asd", "as", "a" };

IEnumerable&lt;string&gt; results =
    from s in input
    let x = s.Length
    select string.Format("{0} ({1})", s, x);

Print(results);</pre>
<p>…and looked at it with <a href="http://www.red-gate.com/products/reflector/" target="_blank">RedGate Reflector</a>,  and remembered how I’d done this before – by introducing an enveloping  anonymous type. Here’s the equivalent using extension methods:</p>
<pre>results = input
    .Select(s =&gt; new { s = s, x = s.Length })
    .Select(e =&gt; string.Format("{0} ({1})", e.s, e.x));</pre>
<p>Both of these queries produce the same results:</p>
<p>asdf (4)   <br />asd (3)    <br />as (2)    <br />a (1)</p>
<p>There’s an object being processed in the pipeline – in this case  it’s a string. The trick is to envelope that object with an anonymous  type so that you can add one or more sibling variables that travel with  it through the pipeline. The variable “e” in this example is the  envelope.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fhow-to-use-let-in-linq-extension-methods%2F&amp;title=How%20to%20Use%20Let%20in%20LINQ%20Extension%20Methods" id="wpa2a_4"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 How to Use Let in LINQ Extension Methods"  title="How to Use Let in LINQ Extension Methods" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/how-to-use-let-in-linq-extension-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/how-to-use-let-in-linq-extension-methods/</feedburner:origLink></item>
		<item>
		<title>How to Use Custom Grouping in LINQ</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/uIW3fIBsalA/</link>
		<comments>http://blog.linqexchange.com/index.php/how-to-use-custom-grouping-in-linq/#comments</comments>
		<pubDate>Fri, 10 Sep 2010 08:59:57 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[group by]]></category>
		<category><![CDATA[groupby]]></category>
		<category><![CDATA[linq c#]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=177</guid>
		<description><![CDATA[You can use LINQ to write queries that perform grouping of data using group by or ordering of data using orderby clause. LINQ provides the default (and the most common) implementation of both of the operations, but sometimes you may need a slightly different behavior when grouping or ordering data (this article is motivated by [...]
No related posts.

Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>You can use LINQ to write queries that perform grouping of data using <code>group by</code> or ordering of data using <code>orderby</code> clause. LINQ provides the default   (and the most common) implementation of both of the operations, but sometimes you    may need a slightly different behavior when grouping or ordering data (this article   is motivated by a <a href="http://stackoverflow.com/questions/2194761/can-i-use-linq-to-retrieve-only-on-change-values">question on StackOverflow</a> which needs to do exactly that for grouping).</p>
<p>Let&#8217;s look at a simple example, which shows when we may need a different behavior when    grouping data. For example, we may have the following list of stock trades   containing a name of a stock and the price of the trade (stored for example as a list   of <code>TradeInfo</code> classes with properties <code>Name</code> and <code>Price</code>):</p>
<pre>{ { Name = "MSFT", Price = 80.00 },
  { Name = "MSFT", Price = 70.00 },
  { Name = "GOOG", Price = 100.00 },
  { Name = "GOOG", Price = 200.00 },
  { Name = "GOOG", Price = 300.00 },
  { Name = "MSFT", Price = 30.00 },
  { Name = "MSFT", Price = 20.00 } }</pre>
<p>Now, we may want to group adjacent trades into a single summary record which will contain   the name of the stock (which is same for all trades in each group), the number of trades    in the group and an average price in the group. The desired results are:</p>
<pre>{ { Name = "MSFT", Count = 2, AvgPrice = 75.00 },
  { Name = "GOOG", Count = 3, AvgPrice = 200.00 },
  { Name = "MSFT", Count = 2, AvgPrice = 25.00 } }</pre>
<p>The operation that we want to do is very similar to <code>group by</code> in LINQ, but    it doesn&#8217;t do quite the same thing! If we used <code>group by</code>, we would get only    two groups as the result. However, as I wrote earlier, we want to group only    <em>adjacent trades</em>. You could write your own extension method to do this,   but then you need to leave the elegant LINQ query syntax. In this article, I&#8217;ll show   you how to get the desired results using a simple LINQ query with a <code>group by</code> clause&#8230;</p>
<h2>Customizing LINQ queries</h2>
<p>Let&#8217;s start by looking how we can customize the meaning of LINQ queries. In fact, you may have already   seen this &#8211; for example the <code>AsParallel</code> method from PLINQ does exactly that.    Anyway, when you write a LINQ query, it is translated by the C# compiler to a sequence of    method calls. The following query groups trades using the standard <code>GroupBy</code> operation provided by LINQ (so the result will be only two groups):</p>
<pre>var agg =
  from t in trades
  group t by t.Name into g
  select new { Name = g.Key, Count = g.Count(),
               AvgPrice = g.Average(t =&gt; t.Price) };
</pre>
<p>Following the rules described in C# specification or using Reflector, we can see what the   compiler does with the above query. The use of <code>group by</code> clause is translated in    a call to <code>GroupBy</code> (an argument is a lambda expression that selects the key we&#8217;re using for   grouping) and the use of <code>select</code> is translated into a call to <code>Select</code> method (an argument is lambda expression returning the anonymous type):</p>
<pre>var agg =
  trades.GroupBy(t =&gt; t.Name).Select(g =&gt;
    new { Name = g.Key, Count = g.Count(),
          AvgPrice = g.Average(t =&gt; t.Price) });
</pre>
<p>This translation is done without checking whether the methods actually exist and what their type   is. In this example, the type of <code>trades</code> is <code>IEnumerable&lt;TradeInfo&gt;</code>.   When compiling the call to <code>GroupBy</code>, the compiler will first look for instance methods   of the interface. It doesn&#8217;t provide any <code>GroupBy</code> method, so it will try finding   some extension method and it will use <code>Enumerable.GroupBy</code>, which is an extension   method for the <code>IEnumerable&lt;T&gt;</code> type.</p>
<p>Now, what can we do if we want to use a different <code>GroupBy</code> method? We need to    instruct the compiler to select a different extension method. We can implement a very simple   method <code>WithAdjacentGrouping</code> which takes <code>IEnumerable&lt;T&gt;</code> and   returns some other interface (we&#8217;ll call it <code>IAdjacentGrouping&lt;T&gt;</code>). The   implementation of the inteface is just a wrapper of <code>IEnumerable&lt;T&gt;</code>, but   it means that C# compiler will use a <em>different type</em> when searching for the   <code>GroupBy</code> method:</p>
<pre>var agg =
  trades.WithAdjacentGrouping()
        .GroupBy(...).Select(...);
</pre>
<p>We&#8217;ll provide our own implementation of the <code>GroupBy</code> method, which groups   only adjacent elements of the input sequence. The method will take an argument of type   <code>IAdjacentGrouping&lt;T&gt;</code>, so when the compiler analyzes the code above,   it will use our method instead of the standard one, which is available in the core   libraries (LINQ to Objects). And of course, this will also work with the LINQ query   syntax, because that is simply translated to method calls. We&#8217;ll look at some nice   queries shortly, but let&#8217;s first implement the required interface and <code>GroupBy</code> method.</p>
<h2>Implementing adjacent grouping</h2>
<p>To implement all the machinery that allows us to use custom <code>GroupBy</code> method,   we need to declare the <code>IAdjacentGrouping&lt;T&gt;</code> interface (including a    concrete class implementing it) and we&#8217;ll also need a class which implements the    <code>IGrouping&lt;T&gt;</code> interface (which represents a group of elements with   a <code>Key</code>). Once that&#8217;s done, we&#8217;ll need two extension methods &#8211; our customized   <code>GroupBy</code> and a method that instructs the compiler to use it (<code>WithAdjacentGrouping</code>).</p>
<h3>Interfaces and classes</h3>
<p>Let&#8217;s start with the <code>IAdjacentGrouping&lt;T&gt;</code> interface. We inherit it from   <code>IEnumerable&lt;T&gt;</code>, which means that all other LINQ query operators (other than   <code>group by</code>) will use the standard implementation. This will have some unfortunate   consequences. All LINQ query operators return <code>IEnumerable&lt;T&gt;</code>, so if we use   any other LINQ operator before our <code>GroupBy</code>, the query will &#8220;not remember&#8221;    our non-standard grouping. This can be solved by providing our own implementations of other   operators (and we&#8217;ll discuss this in details later). Other than inheriting from <code>IEnumerable&lt;T&gt;</code> our new interface will not have any members, because we need it only to carry   type information through the query:</p>
<pre>interface IAdjacentGrouping&lt;T&gt; : IEnumerable&lt;T&gt; {
} 

class WrappedAdjacentGrouping&lt;T&gt; : IAdjacentGrouping&lt;T&gt; {
  public IEnumerable&lt;T&gt; Wrapped { get; set; } 

  public IEnumerator&lt;T&gt; GetEnumerator() {
    return Wrapped.GetEnumerator();
  }
  IEnumerator IEnumerable.GetEnumerator() {
    return (IEnumerator)GetEnumerator();
  }
}
</pre>
<p>The class <code>WrappedAdjacentGrouping&lt;T&gt;</code> is a simple implementation of our   new interface. It wraps an <code>IEnumerable&lt;T&gt;</code> value and delegates all    operations to the wrapped type, so this is pretty uninteresting boilerplate code.</p>
<p>We&#8217;ll need one more trivial class. A typical grouping operation takes a list of elements    and returns a list of lists (that is, a list of groups where each group consists of    one or more inidividual elements). In LINQ, this is usually done by returning a value   of type <code>IEnumerable&lt;IGrouping&lt;TKey, T&gt;&gt;</code>. The    <code>IGrouping&lt;TKey, T&gt;</code> type is just like <code>IEnumerable&lt;T&gt;</code> with one additional feature &#8211; it has a property <code>Key</code>, which returns the    key used to identify the group (in our earlier example, the key would be the name   of the stock such as <code>GOOG</code> or <code>MSFT</code>). Since    <code>IGrouping&lt;TKey, T&gt;</code> is an interface and .NET libraries don&#8217;t provide   any simple implementation of the interface, we&#8217;ll need to write our own:</p>
<pre>class Grouping&lt;K, T&gt; : IGrouping&lt;K, T&gt; {
  public K Key { get; set; }
  public IEnumerable&lt;T&gt; Elements;

  public IEnumerator&lt;T&gt; GetEnumerator() {
    return Elements.GetEnumerator();
  }
  IEnumerator IEnumerable.GetEnumerator() {
    return (IEnumerator)GetEnumerator();
  }
}
</pre>
<p>The class stores elements of the group in a property <code>Elements</code>, which will be   usually accessed via the <code>IEnumerable&lt;T&gt;</code> interface (both generic and    non-generic <code>GetEnumerator</code> methods just delegate the operation to the wrapped   collection). The class also has a property <code>Key</code> with a getter (required by the   interface) and setter (so that we can use it easily). Now that we have all the boilerplate   code, let&#8217;s look at more interesting things. In the next section, we&#8217;ll implement our   custom grouping.</p>
<h3>Implementing custom grouping</h3>
<p>Our custom <code>GroupBy</code> method has exactly the same type signature as the   <code>GroupBy</code> method provided by LINQ (with the only exception that it takes   the <code>IAdjacentGrouping&lt;T&gt;</code> as the first argument). It implements the behavior discussed   in the introduction. Instead of grouping <em>all elements</em> into groups based on    the returned keys, it groups all <em>adjacent elements</em> with the same key from the    input collection.</p>
<p>The implementation of this functionality is the only lengthy piece of code in this article.   We&#8217;ll need to store a collection of elements in the current group (grouped so far) with   a key of the current group. Each time we move to the next element, we&#8217;ll check if it has the    same key as the current group or not. If the key didn&#8217;t change, we&#8217;ll just add the element   to the current group and continue. If the key changes, we&#8217;ll return the previous group   and start a new one. We also need to deal specially with the first element:</p>
<pre>public static IEnumerable&lt;IGrouping&lt;K, T&gt;&gt; GroupBy&lt;T, K&gt;
    (this IAdjacentGrouping&lt;T&gt; source, Func&lt;T, K&gt; keySelector) where K : IComparable {
  // Remembers elements of the current group
  List&lt;T&gt; elementsSoFar = new List&lt;T&gt;();
  IEnumerator&lt;T&gt; en = source.GetEnumerator(); 

  // Read the first element (we need an initial key value)
  if (en.MoveNext()) {
    K lastKey = keySelector(en.Current);
    do {
      // Test whether current element starts a new group
      K newKey = keySelector(en.Current);
      if (newKey.CompareTo(lastKey) != 0)
      {
        // Yield the previous group and start next one
        yield return new Grouping&lt;K, T&gt;
          { Elements = elementsSoFar, Key = lastKey };
        lastKey = newKey;
        elementsSoFar = new List&lt;T&gt;();
      } 

      // Add element to the current group
      elementsSoFar.Add(en.Current);
    }
    while (en.MoveNext()); 

    // Yield the last group of sequence
    yield return new Grouping&lt;K, T&gt;
      { Elements = elementsSoFar, Key = lastKey };
  }
}
</pre>
<p>We&#8217;re using the <code>IEnumerator&lt;T&gt;</code> to iterate over the source elements,   because this allows us to call the <code>MoveNext</code> once before we start looping    (to get the key of the first element, which is also the key of the first group). Once   we initialize the <code>lastKey</code> variable, we start looping until the source    is exhausted. Note that our method has a generic constraint saying that the key   should be <code>IComparable</code>. This allows us to compare keys (and decide whether to   start a new group or not) using the <code>CompareTo</code> method.</p>
<p>The last thing we need to do is to implement the <code>WithAdjacentGrouping</code> method,   which instructs the compiler to use our <code>GroupBy</code>. As discussed earlier, the method   will change the type of the collection from <code>IEnumerable&lt;T&gt;</code> to our    type <code>IAdjacentGrouping&lt;T&gt;</code>, so that the compiler will prefer our   <code>GroupBy</code> method (because it is an extension method directly for the    <code>IAdjacentGrouping&lt;T&gt;</code> type):</p>
<pre>public static IAdjacentGrouping&lt;T&gt; WithAdjacentGrouping&lt;T&gt;(this IEnumerable&lt;T&gt; e) {
  return new WrappedAdjacentGrouping&lt;T&gt; { Wrapped = e };
}
</pre>
<p>The extension method is trivial. It simply returns our concrete implementation of the interface,    which wraps an <code>IEnumerable&lt;T&gt;</code>. This was the last missing piece that   we needed to implement, before we could use our grouping operation in LINQ queries, so let&#8217;s   look at a couple of examples showing how this can be used.</p>
<h2>Grouping trades and other examples</h2>
<p>First of all, let&#8217;s look at the example, which I presented as a motivation at the beginning   of this article. We can use our new extension method <code>WithAdjacentGrouping</code> to change   the meaning of a <code>group by</code> clause in a query. When we use the extension method,   the query will group only adjacent elements, which is exactly what we wanted:</p>
<pre>var groups =
  from t in trades.WithAdjacentGrouping()
  group t by t.Name into g
  select new {
    Name = g.Key, Count = g.Count(),
    AvgPrice = g.Average(t =&gt; t.Price) };
</pre>
<p>The query uses the value specified in the <code>by</code> clause to decide whether   to start a new group or whether an element belongs to the current group. This means   that it will start a new group each time the <code>t.Name</code> value changes. When   that happens, it will use the <code>select</code> clause to generate aggregate   information about the group. In this case, we return the number of elements and   an average price in the group. If you run the query with the input data from the   beginning of the article, you&#8217;ll get the following result:</p>
<pre>{ { Name = "MSFT", Count = 2, AvgPrice = 75.00 },
  { Name = "GOOG", Count = 3, AvgPrice = 200.00 },
  { Name = "MSFT", Count = 2, AvgPrice = 25.00 } }</pre>
<p>I&#8217;m sure you can imagine other situations when this grouping technique would be useful.   It also seems to be useful when processing Open XML documents as mentioned by   <a href="http://blogs.msdn.com/ericwhite/archive/2008/04/21/the-groupadjacent-extension-method.aspx">Eric White</a> (who shows how to implement this behavior using an ordinary extension method).   However, we&#8217;ll look at one more interesting aspect of this implementation of grouping &#8211;    the fact that it can work with <em>infinite sequences</em>.</p>
<h3>Grouping prime numbers</h3>
<p>An infinite sequence is an <code>IEnumerator&lt;T&gt;</code> that always returns   <code>true</code> when you call its <code>MoveNext</code> method. They do not represent   elements of a collection (because an infinite collection wouldn&#8217;t fit in a memory!), but   we can easily generate them in C# using the <code>yield return</code> keyword.</p>
<p>The usual implementation of <code>GroupBy</code> cannot work on infinite sequences,   because it needs to see all elements of the sequence, before it can give any result    (we can&#8217;t return any group early, because there may still be some element that belongs   to that group in the rest of the sequence). However, our implementation which groups    only adjacent elements return a group immediately when the key calculated for the    current element changes. This means that it needs to see only a limited number of   elements before returning the next group.</p>
<p>Let&#8217;s look at an example that shows how we can use this property in practice.    The following code shows how to generate an infinite <code>IEnumerable&lt;long&gt;</code> value, which will contain prime numbers (it is still somehow limited, because we&#8217;re   using <code>long</code>, but we could use for example the new <code>BigInteger</code> from .NET 4.0):</p>
<pre>static bool IsPrime(long n) {
  long max = (long)Math.Sqrt(n);
  for (long i = 2; i &lt;= max; i++)
    if (n % i == 0) return false;
  return true;
}
static IEnumerable&lt;long&gt; Primes() {
  for (long n = 0; true; n++)
    if (IsPrime(n)) yield return n;
}
</pre>
<p>Now, let&#8217;s say that we want to count the number of primes in groups of 100000 numbers.   It is a well known fact that for intervals of the same length (in our case, 100000) the   number of primes will be larger for smaller numbers (e.g. interval from 0 to 100000)    and smaller once we move to larger numbers (e.g. interval from 500000 to 600000).    We can verify this fact using the following query:</p>
<pre>var primeGroups =
  from n in Primes().WithAdjacentGrouping()
  group n by (n / 100000) into g
  select g.Count();
</pre>
<p>If you take first 10 results of the query (for example using <code>Take(10)</code>),   it will give the following numbers:</p>
<pre>9594, 8392, 8013, 7863, 7678, 7560, 7445, 7408, 7323, 7224</pre>
<p>If you wanted to take all results of the query (e.g. using just <code>foreach</code>),   it would continue printing results forever (and get slower and slower, because testing   whether a large number is prime can take quite long). If you forget to add the    <code>WithAdjacentGrouping</code> method and run the code using the ordinary    <code>GroupBy</code> method, it will never print any result (because the standard    <code>GroupBy</code> operator tries to read <em>all</em> numbers from the infinite sequence).</p>
<h3>Ascending and descending groups</h3>
<p>So far, we have been using <code>group by</code> to group adjacent elements with the same key.   The standard LINQ implementation gives us <code>group by</code> which groups all elements   using the given key. However, we can imagine other ways to group elements. For example,   you could create groups of values for which the value of the key is ascending or descending.    This can be used for example to simply show trends in a sequence of data.</p>
<p>Let&#8217;s say we have a sequence (ordered by time) which contains stock prices (of a single   stock) or for example currency exchange rate. The data may look like this:</p>
<pre>{ { Price = 80.00, Time = 8:00 },
  { Price = 70.00, Time = 9:00 },
  { Price = 50.00, Time = 10:00 },
  { Price = 55.00, Time = 11:00 },
  { Price = 60.00, Time = 12:00 },
  { Price = 75.00, Time = 13:00 },
  { Price = 65.00, Time = 14:00 } }</pre>
<p>Now, you can see that there is a descending sequence from 8:00 to 10:00, then we have   an ascending sequence from 10:00 to 13:00 and finally, there is a short descending sequence   from 13:00 to 14:00. If we want to simply visualize these trends, we would like to   aggregate these three groups into the following result:</p>
<pre>{ { Difference = -30.00, Interval = 2:00 },
  { Difference = +25.00, Interval = 3:00 },
  { Difference = -10.00, Interval = 1:00 } }</pre>
<p>This operation is quite similar to the one which motivated this article, but it    is different. We cannot implement it using our <code>WithAdjacentGrouping</code> method.    However, after reading this article, you&#8217;d be able to follow the pattern and define your   own extension method (for example <code>WithTendencyGrouping</code>) and your own   custom implementation of <code>GroupBy</code>, which implements the behavior we just   described. Then you could write the following code:</p>
<pre>var trens =
  from s in stocks.WithTendencyGrouping()
  group s by s.Price into g
  select new {
    Difference = g.Last().Price - g.First().Price,
    Interval = g.Last().Time - g.First().Time };
</pre>
<p>With an appropriate custom implementation of <code>GroupBy</code> method, this code would   give the results we&#8217;ve seen earlier. As you can see, the <code>group by</code> clause    can be customized to perform various useful tasks.</p>
<h2>Summary</h2>
<p>In this article, we discussed two alternative implementations of the <code>GroupBy</code> operator (in addition to the standard implementation provided by LINQ). We&#8217;ve seen that   we can change the meaning of LINQ query syntax to use our own implementation of    <code>GroupBy</code>. Then we can write readable and elegant LINQ queries to group   data in a non-standard way (for example by grouping adjacent elements with the same    value of the key). You could use the techniques discussed in this article to customize    other clauses of LINQ queries (for example the <code>orderby</code> clause).</p>
<p>We didn&#8217;t discuss one important thing. Once you use other operator in the LINQ query   (for example <code>where</code>), the compiler &#8220;forgets&#8221; that we wanted to use custom   <code>GroupBy</code> method. This happens because it selects the standard <code>Where</code> method and gives it our wrapped sequence of type <code>IAdjacentGrouping&lt;T&gt;</code>.   However, the <code>Where</code> method returns the result of type <code>IEnumerable&lt;T&gt;</code>,   so if the compiler needs to invoke <code>GroupBy</code> on the result, it will pick a standard   overload. This problem can be easily solved by providing our own implementations for    all the standard LINQ query operators. For example, we would implement a <code>Where</code> method,   which returns the result as <code>IAdjacentGrouping&lt;T&gt;</code>. The implementations of these   methods would be quite easy (because they just wrap standard methods), but it would   make the code rather lengthfy, so I didn&#8217;t include them in the article.</p>
<p>Finally, this article has been inspired by a <a href="http://stackoverflow.com/questions/2194761/can-i-use-linq-to-retrieve-only-on-change-values">question on StackOverflow</a> [<a href="http://stackoverflow.com/questions/2194761/can-i-use-linq-to-retrieve-only-on-change-values" target="_blank">^</a>]   and by a paper by Philip Wadler and Simon Peyton Jones about <a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/list-comp/list-comp.pdf">Haskell comprehensions</a> [<a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/list-comp/list-comp.pdf" target="_blank">^</a>]    (Haskell comprehensions were one of the motivations for LINQ). The paper adds support for <code>order</code> and <code>group</code> to the comprehension syntax (LINQ was one of the motivations of the paper). In Haskell, you can    provide your own function directly in the syntax. Here is a Haskell version of our original   example with grouping stock trades:</p>
<pre>[ (the stock, length stock, average price)
| (stock, price) &lt;- trades
, group by stock using groupRun ]</pre>
<p>The important thing about the example that it uses <code>using</code> clause which allows you to    specify your own grouping function. In this case, the grouping function is <code>groupRun</code>,   which implements the same functionality as our custom <code>GroupBy</code> grouping adjacent elements.   The paper also states that in LINQ, it isn&#8217;t possible to provide custom grouping (or ordering)   function. I believe that this article shows that this isn&#8217;t quite true &#8211; you can do similar thing   in LINQ. However, there are many limitaions in LINQ. In particular, we can specify one grouping   function for the whole query and cannot change it for each <code>group by</code> clause.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fhow-to-use-custom-grouping-in-linq%2F&amp;title=How%20to%20Use%20Custom%20Grouping%20in%20LINQ" id="wpa2a_6"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 How to Use Custom Grouping in LINQ"  title="How to Use Custom Grouping in LINQ" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/how-to-use-custom-grouping-in-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/how-to-use-custom-grouping-in-linq/</feedburner:origLink></item>
		<item>
		<title>How to Implement Paging with LINQ</title>
		<link>http://feedproxy.google.com/~r/LinqExchange/~3/K8JMFTms8UE/</link>
		<comments>http://blog.linqexchange.com/index.php/how-to-implement-paging-with-linq-3/#comments</comments>
		<pubDate>Thu, 26 Aug 2010 08:48:52 +0000</pubDate>
		<dc:creator>LINQ Master</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[linq c#]]></category>
		<category><![CDATA[linq to sql]]></category>

		<guid isPermaLink="false">http://blog.linqexchange.com/?p=174</guid>
		<description><![CDATA[Before going into how paging is implemented with LINQ, Let&#8217;s discuss the need for implementing paging. With large amounts of data, it is not a good practice to pull all records from database when you are showing a fraction of them in one page. It is always recommended to use data on demand approach. When [...]
No related posts.

Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.]]></description>
			<content:encoded><![CDATA[<p>Before going into how paging is implemented with LINQ, Let&#8217;s discuss the need for implementing paging.</p>
<p>With  large amounts of data, it is not a good practice to pull all records  from database when you are showing a fraction of them in one page. It is  always recommended to use data on demand  approach. When you want to show first 20 records out of the search  results then you must get the first 20 records from database and discard  the rest. Similarly when you want to show next 20 records of the search  results then you need to get the next 20 records from database and  discard the rest. This is nothing but called paging.</p>
<p>LINQ has made the paging solution very simple as shown below example.</p>
<pre class="brush: csharp">
public List&lt;Client>
GetAllClients(bool? isActive, int pageNumber, int pageSize, out int totalPages)
{
//Actual query which returns large data
var query = dataContext.Clients.Where(p => isActive == null || p.IsActive == isActive);

//Calculating total number of pages by taking ceiling number of the fractional value
totalPages = (int)Math.Ceiling((decimal)query.Count() / (decimal)pageSize);

//Paging logic goes here
return query.Skip((pageNumber - 1)*pageSize).Take(pageSize).ToList();
}
</pre>
<p>The parameters which play major role in paging are page number and page  size. The page number is to identify the page of which the records to be  returned. And the page size to identify the number of records to be  returned. And there is another out parameter totalPages which is used to  hold the total number of pages available within the data returned. This  is needed to show the number of pages to the user and also useful in  the logic which enables/disables page navigation.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fhow-to-implement-paging-with-linq-3%2F&amp;title=How%20to%20Implement%20Paging%20with%20LINQ" id="wpa2a_8"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 How to Implement Paging with LINQ"  title="How to Implement Paging with LINQ" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.linqexchange.com/index.php/how-to-implement-paging-with-linq-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://blog.linqexchange.com/index.php/how-to-implement-paging-with-linq-3/</feedburner:origLink></item>
		<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://yarpp.org'>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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Flinq-tolookup-vs-todictionary%2F&amp;title=LINQ%20ToLookup%20vs%20ToDictionary" id="wpa2a_10"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 LINQ ToLookup vs ToDictionary"  title="LINQ ToLookup vs ToDictionary" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</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://yarpp.org'>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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fimplementing-linq-on-the-net-micro-framework%2F&amp;title=Implementing%20LINQ%20on%20the%20.NET%20Micro%20Framework" id="wpa2a_12"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 Implementing LINQ on the .NET Micro Framework"  title="Implementing LINQ on the .NET Micro Framework" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</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://yarpp.org'>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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fhow-to-use-except-with-equalitycomparer%2F&amp;title=How%20to%20Use%20.Except%20with%20EqualityComparer%3CT%3E" id="wpa2a_14"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 How to Use .Except with EqualityComparer<T>"  title="How to Use .Except with EqualityComparer<T>" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</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://yarpp.org'>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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fuse-linq-and-reflection-to-find-matching-properties%2F&amp;title=Use%20LINQ%20and%20Reflection%20to%20Find%20Matching%20Properties" id="wpa2a_16"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 Use LINQ and Reflection to Find Matching Properties"  title="Use LINQ and Reflection to Find Matching Properties" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</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://yarpp.org'>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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fguidelines-and-best-practices-in-optimizing-linq-performance%2F&amp;title=Guidelines%20and%20Best%20Practices%20in%20Optimizing%20LINQ" id="wpa2a_18"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 Guidelines and Best Practices in Optimizing LINQ"  title="Guidelines and Best Practices in Optimizing LINQ" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</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://yarpp.org'>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 a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fblog.linqexchange.com%2Findex.php%2Fwhy-you-need-to-know-linq-to-xml%2F&amp;title=Why%20You%20Need%20to%20Know%20LINQ%20to%20XML" id="wpa2a_20"><img src="http://blog.linqexchange.com/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="share save 171 16 Why You Need to Know LINQ to XML"  title="Why You Need to Know LINQ to XML" /></a></p><p>No related posts.</p>
<p>Related posts brought to you by <a href='http://yarpp.org'>Yet Another Related Posts Plugin</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>
	</channel>
</rss><!-- Dynamic Page Served (once) in 1.043 seconds --><!-- Cached page served by WP-Cache -->
