<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Equivalence &#187; LINQ</title>
	<atom:link href="http://www.equivalence.co.uk/archives/category/linq/feed" rel="self" type="application/rss+xml" />
	<link>http://www.equivalence.co.uk</link>
	<description>Technical Blog for Software Developers</description>
	<lastBuildDate>Wed, 21 Apr 2010 22:30:08 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>dynamic queries with LINQ</title>
		<link>http://www.equivalence.co.uk/archives/819</link>
		<comments>http://www.equivalence.co.uk/archives/819#comments</comments>
		<pubDate>Tue, 10 Mar 2009 21:56:03 +0000</pubDate>
		<dc:creator>Gregg</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[dynamic LINQ query]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[Expressions]]></category>
		<category><![CDATA[where parameters]]></category>

		<guid isPermaLink="false">http://www.equivalence.co.uk/?p=819</guid>
		<description><![CDATA[So, I&#8217;m a master C# programmer having been using it for a grand total of 4 weeks! My learning process began by ignoring the provincial and proverbial &#8220;Hello World&#8221; program, and instead I decided to learn the language features that are particular to C#. As it happens, C# has quite a few modern language features [...]]]></description>
			<content:encoded><![CDATA[<p>So, I&#8217;m a master C# programmer having been using it for a grand total of 4 weeks! My learning process began by ignoring the provincial and proverbial &#8220;Hello World&#8221; program, and instead I decided to learn the language features that are particular to C#.</p>
<p>As it happens, C# has quite a few modern language features that Java is sadly lacking (I won&#8217;t go into this here, but a comparison between the two is something I plan to blog about in the future). Along with many other new features, C# 3.0 gave us LINQ, which will be the topic of this post.</p>
<p>LINQ, I think, is reasonably straightforward to both understand and comprehend. Basic queries are extremely simple to create, and LINQ almost gives C# a functional programming feel. An example LINQ query is shown below:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">from s <span style="color: #0600FF;">in</span> students where s.<span style="color: #0000FF;">classyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2008&quot;</span> <span style="color: #008000;">&amp;&amp;</span> s.<span style="color: #0000FF;">courseyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2&quot;</span> select s<span style="color: #008000;">;</span></pre></div></div>

<p>That said, not everything is plain sailing with LINQ. The application I was writing required the where condition in my LINQ statement be dynamic. That is, a column specified in the where condition is only known at runtime. Achieving this functionality using the syntax shown above is not possible (which if you try it out I&#8217;m sure it will be clear why). To achieve this functionality the learning curve soon ramped up.</p>
<p>If you have searched on Google for dynamic queries in LINQ, you probably found these two articles, ScottGu&#8217;s <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx">Dynamic Linq</a> and tomasp.net&#8217;s <a href="http://tomasp.net/articles/dynamic-linq-queries.aspx">Building LINQ Queries at Runtime in C#</a> - there were others, but few proved to be much help. ScottGu&#8217;s article was very good, and in essence solved my problem, but didn&#8217;t really help me understand the problem. The second article just went way over my head. Why? Well it came down to another new feature of C# that I didn&#8217;t know about, which was <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx">Expressions and Expression Trees</a>, which, as it turns out, proved to be the key to solving this problem.</p>
<p>In addition to using the query syntax with LINQ (as shown above), you can also use query expressions. Query expressions are simply static methods that allow you to express a LINQ query. The example given above can be rewritten as follows using a query expression:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">student.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>s <span style="color: #008000;">=&gt;</span> s.<span style="color: #0000FF;">courseyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2008&quot;</span> <span style="color: #008000;">&amp;&amp;</span> s.<span style="color: #0000FF;">classyear</span> <span style="color: #008000;">==</span> <span style="color: #666666;">&quot;2&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>On first looking at this example, it is still not obvious how runtime queries can be generated using query expressions. However, by taking a look at the type of the argument passed to <code>Where</code> helps us out:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>TSource, <span style="color: #FF0000;">bool</span><span style="color: #008000;">&gt;&gt;</span> predicate</pre></div></div>

<p>After some thought, this begins to make sense. The <code>Where</code> method takes a lambda expression whose parameter is of type <code>TSource</code> and returns a boolean. Therefore, surely we can create a lambda expression dynamically by building an expression tree for it? And yes, this is exactly what you are supposed to do.</p>
<p>C# experts are probably howling at me now and can&#8217;t understand why it took me so long to get there. However, this article is not aimed at you; it&#8217;s aimed at a newbie like me, and is simply trying to detail my thought process.</p>
<p>So now it was time to learn about Expression Trees.</p>
<p>Although I understood the concept of Expression Trees, they took a bit of getting used to &#8211; just don&#8217;t give up if you are struggling with it. In order to show how we can use Expression Trees to create dynamic queries, I will jump straight in with the code:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>student, <span style="color: #FF0000;">bool</span><span style="color: #008000;">&gt;&gt;</span> GetWhereLambda<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> courseyear,
                                                      <span style="color: #FF0000;">string</span> classyear,
                                                      <span style="color: #FF0000;">string</span> myDynaColumn<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    ParameterExpression param <span style="color: #008000;">=</span> Expression.<span style="color: #0000FF;">Parameter</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #000000;">&#40;</span>student<span style="color: #000000;">&#41;</span>, <span style="color: #666666;">&quot;s&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    Expression courseExpr <span style="color: #008000;">=</span> GetEqualsExpr<span style="color: #000000;">&#40;</span>param, <span style="color: #666666;">&quot;courseyear&quot;</span>, courseyear<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    Expression classExpr <span style="color: #008000;">=</span> GetEqualsExpr<span style="color: #000000;">&#40;</span>param, <span style="color: #666666;">&quot;classyear&quot;</span>, classyear<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    Expression cond <span style="color: #008000;">=</span> Expression.<span style="color: #0000FF;">And</span><span style="color: #000000;">&#40;</span>courseExpr, classExpr<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// This is where we create the expression for the dynamic column.</span>
    <span style="color: #008080; font-style: italic;">// Obviously the value could have been dynamic as well but it </span>
    <span style="color: #008080; font-style: italic;">// saves a little visual complexity this way.</span>
    cond <span style="color: #008000;">=</span> Expression.<span style="color: #0000FF;">And</span><span style="color: #000000;">&#40;</span>cond, GetEqualsExpr<span style="color: #000000;">&#40;</span>param, myDynaColumn, <span style="color: #666666;">&quot;YES&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> Expression.<span style="color: #0000FF;">Lambda</span><span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>student, <span style="color: #FF0000;">bool</span><span style="color: #008000;">&gt;&gt;</span><span style="color: #000000;">&#40;</span>cond, param<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> Expression GetEqualsExpr<span style="color: #000000;">&#40;</span>ParameterExpression param,
                                 <span style="color: #FF0000;">string</span> property,
                                 <span style="color: #FF0000;">string</span> value<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
     Expression prop <span style="color: #008000;">=</span> Expression.<span style="color: #0000FF;">Property</span><span style="color: #000000;">&#40;</span>param, property<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
     Expression val <span style="color: #008000;">=</span> Expression.<span style="color: #0000FF;">Constant</span><span style="color: #000000;">&#40;</span>value<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
     <span style="color: #0600FF;">return</span> Expression.<span style="color: #0000FF;">Equal</span><span style="color: #000000;">&#40;</span>prop, val<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p>Seeing the code makes this look pretty simple, but there are quite a few concepts that a programmer new to C# has to get the hang of. However, let&#8217;s just step through the code &#8211; well one clause anyway, the rest follows from that.</p>
<p>Let&#8217;s look at how the clause <code>(s.courseyear == "2008")</code>, from out original where condition, converts to an Expression. We first create a parameter expression (Line 5), that is, the argument (parameter) supplied to the lambda expression (this parameter must be used for all sub-expressions that make up the lambda expression). Next, we need to create an expression to represent the right hand-side (<code>s.courseyear</code>) and left hand-side (<code>"2008"</code>) of our clause. Since <code>courseyear</code> is a property of <code>student</code> (property as in <a href="http://msdn.microsoft.com/en-us/library/x9fsa0sw(VS.80).aspx">C# property</a> &#8211; think neat getters and setters) we create a property expression, i.e. <code>prop = Expression.Property(param, "courseyear")</code>, and as <code>"2008"</code> is really a constant, we create constant expression using <code>value = Expression.Constant("2008")</code>. Finally, we want to express the fact that the property should be equal to the constant in our query, we use the <code>Expression.Equal(prop,value)</code>. That&#8217;s it. Essentially what expressions do is model our code as data.</p>
<p>Now it becomes obvious how we can represent a column in the where clause that is supplied at runtime &#8211; we simply create a property expression, as shown at Line 20, where <code>property</code> is the dynamic column name specified at runtime.</p>
<p>To combine the clauses in the where condition we simply use <code>Expression.And</code>, as shown in Lines 9 and 11. The resulting expression and the parameter is then used to create a lambda expression, which is in turn passed as an argument to <code>Where</code>, e.g.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Expression<span style="color: #008000;">&lt;</span>Func<span style="color: #008000;">&lt;</span>student, <span style="color: #FF0000;">bool</span><span style="color: #008000;">&gt;&gt;</span> myLambda <span style="color: #008000;">=</span> GetWhereLambda<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;2008&quot;</span>, <span style="color: #666666;">&quot;2&quot;</span>, <span style="color: #666666;">&quot;active&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
IEnumerable<span style="color: #008000;">&lt;</span>student<span style="color: #008000;">&gt;</span> filtered <span style="color: #008000;">=</span> students.<span style="color: #0000FF;">Where</span><span style="color: #000000;">&#40;</span>myLambda<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>There you have it. It&#8217;s not that straightforward for those new to C# like me, but hopefully this article at least gives some code that can easily be used by people in the same position as I was.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.equivalence.co.uk/archives/819/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
