Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to simplify complicated conditional clauses when using LINQ to SQL
    primarykey
    data
    text
    <p>Complicated statements with lots of AND/OR compenents are horrible to read and prone to errors - in a normal IF statement I might make use of a method call to simplify the is statement - for example:</p> <pre><code> if (((user == myUser || user == yourUser) &amp;&amp; user != Admin) &amp;&amp; Something &gt; SomethingElse &amp;&amp; (thresholdDate &gt; item.itemDate || (item.itemDate == null &amp;&amp; item.itemType == itemIsDated)) ) { DoStuff(); } </code></pre> <p>I could refactor out the user and date parts to make things easier to read:</p> <pre><code> if ( UserValid(user) &amp;&amp; Something &gt; SomethingElse &amp;&amp; DateIsValid(thresholdDate, item) ) { DoStuff(); } </code></pre> <p>What can I do in a LINQ query to simplifiy the nested IF?</p> <p>For example if I have something along the lines of:</p> <pre><code> var someResults = DataManager.Things .Where(item =&gt; (item.UserName == currentUser.UserName || item.ParentUsername == currentUser.UserName) &amp;&amp; (item.ItemType == (int) ItemType.MyType || item.ItemType == (int) ItemType.YourType) &amp;&amp; item.Result == null &amp;&amp; ( (item.Status == null &amp;&amp; (item.ItemDate &lt; thresholdDate || item.ItemType == (int) ItemType.YourType) ) || (item.Status != null &amp;&amp; item.Status != "Rejected") ) ) </code></pre> <p>** not actual code - just a simplified and generic example.</p> <p>I'd like to be able to extract parts of the logic into methods - or in some other way seperate out the AND / OR mess such that it's clear what is going on.</p> <p>I've tried adding a method to the 'item' to perfrom some of the logic a kind of IsValidType(typeOptions) method - this compiles fine but LINQ complains that it does't recognise the method at runtime.</p> <p>I could use a property on the item - but then I can't pass any context information (which makes it of limited use)</p> <p>How do you go about making this kind of query readable?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    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.
    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