Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to reuse a linq expression for 'Where' when using multiple source tables
    text
    copied!<p>Let's have the following:</p> <pre><code>public interface IOne { UInt64 Id { get; } Int16 Size { get; } } public interface ITwo { UInt64 OneId { get; } Int16 Color { get; } } </code></pre> <p>As explained <a href="https://stackoverflow.com/questions/986877/how-can-i-reuse-expressions-within-linq-statements">here</a> the way to reuse a linq expression is to write something like this:</p> <pre><code>public static Expression&lt;Func&lt;IOne, bool&gt;&gt; MyWhereExpression( int value ){ return (o) =&gt; (o.Size &gt; value); } int v = 5; IQueryable&lt;IOne&gt; records = from one in s.Query&lt;IOne&gt;() .Where(MyWhereExpression(v)) select one; </code></pre> <p>When I want to do the same with two tables I encounter a problem.</p> <p>The expression:</p> <pre><code>public static Expression&lt;Func&lt;IOne, ITwo, bool&gt;&gt; MyWhereExpression2(int color ) { return (one,two) =&gt; (one.Id == two.OneId) &amp;&amp; (two.Color &gt; color ); } </code></pre> <p>Linq 1:</p> <pre><code>int color = 100; IQueryable&lt;IOne&gt; records = from one in s.Query&lt;IOne&gt;() from two in s.Query&lt;ITwo&gt;() .Where(MyWhereExpression2(color)) select one; </code></pre> <p>This doesn't work as <em>.Where</em> sticks to only the 2nd <em>from</em>.</p> <p>Linq 2:</p> <pre><code>int color = 100; IQueryable&lt;IOne&gt; records = (from one in s.Query&lt;IOne&gt;() from two in s.Query&lt;ITwo&gt;() select new { one, two }) .Where(MyWhereExpression2(color)); </code></pre> <p>This results in </p> <blockquote> <p>Argument 2: cannot convert from 'Expression&lt;System.Func&lt;IOne,ITwo,bool>>' to 'System.Func&lt;AnonymousType#1,int,bool>'</p> </blockquote> <p>I understand the error message about the AnonymousType, but I cannot figure out how to write the query.</p> <p>The reason why I want to use an expression rather than just write</p> <pre><code>where (one.Id == two.OneId) &amp;&amp; (two.Color &gt; color ) </code></pre> <p>directly in the linq query is because I want to reuse this expression in multiple linq queries. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload