Note that there are some explanatory texts on larger screens.

plurals
  1. POSpliting up long linq queries for improved maintainability
    primarykey
    data
    text
    <p>I have a bunch of these Tasks that are all based on LINQ queries. I am looking for good way to refactor them and make them easier to read and allow me to change the queries depending on language/region etc.</p> <pre><code>var mailTaskOne = CreateTask(() =&gt; myService.Mail.Where(p =&gt; p.ProjectName == "Delta" &amp;&amp; (p.MailLang== (int)MailLanguage.EU || p.MailLang == (int)MailLanguage.RU) &amp;&amp; (p.DateEntered &gt;= startDate &amp;&amp; p.DateEntered &lt;= endDate) &amp;&amp; p.MailPriority == (int)MailPriority.High).Count()); </code></pre> <p>One of the ways I thought would be convenient would be to split the query up into something like this.</p> <pre><code>var results = myService.Mail.Where(x =&gt; x.ProjectName == "Delta"); results = results.Where(p =&gt; p.MailLang== (int)MailLanguage.EU); results = results.Where(p =&gt; p.DateModified &gt;= startDate &amp;&amp; p.DateModified &lt;= endDate); </code></pre> <p>This would allow me to do this without having to repeat the whole query for each region.</p> <pre><code>if (MailLanguage == "English") results = results.Where(p =&gt; p.MailLang== (int)MailLanguage.EU); else results = results.Where(p =&gt; p.MailLang== (int)MailLanguage.RU); </code></pre> <p>Is there anyone that knows a better solution for this? I end up having huge functions as I need to do maybe 20 of these queries depending on the requirements; such as Region, Project name etc.</p> <hr> <p><strong>Edit:</strong></p> <p>Due to some limitations I did not know of with the back-end (web service/api) I could unfortunately not use some of the awesome answers mentioned in this question.</p> <p>For example this does not get translated properly, but in no ways because the answer incorrect, simply does not work with the API I am working against -- possibly because it is poorly implemented. </p> <pre><code>public bool IsValid(Type x) { return (x.a == b) &amp;&amp; (x.c ==d) &amp;&amp; (x.d == e); } </code></pre> <p>Anyway, anyone looking for similar solutions all of these are valid answers, but in the end I ended up going with something similar to the solution snurre provided.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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