Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Well, the <code>Select(el =&gt; el)</code> isn't doing you any good to start with.</p> <p>I suggest you use <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.singleordefault.aspx" rel="nofollow noreferrer"><code>SingleOrDefault</code></a>:</p> <pre><code>var productId = element.Elements("ProductId").SingleOrDefault(); if (productId != null) filter.ProductId = Convert.ToInt32(productId.Value); </code></pre> <p>Note that that handles the case where there are <em>no</em> ProductId elements, but will throw an exception if there's <em>more than one</em>. If that's actually a valid case, then your current code (without the redundant <code>Select</code> call) is reasonable.</p> <p>EDIT: You <em>could</em> get away from this with:</p> <pre><code>var productId = element.Elements("ProductId") .Select(elt =&gt; elt.Value) .SingleOrDefault(); filter.ProductId = Convert.ToInt32(productId ?? filter.ProductId.ToString()); </code></pre> <p>But that's pretty ghastly ;)</p> <p>Basically you've got a condition - you only want to set the <code>ProductId</code> if it's specified. An "if" statement is the generally accepted way of conditionally executing code :)</p> <p>There are alternatives:</p> <pre><code>filter.ProductId = productId == null ? filter.ProductId : int.Parse(productId); </code></pre> <p>If you don't mind <code>filter.ProductId</code> being set to 0 if there's no ID specified, then you can just use:</p> <pre><code>filter.ProductId = Convert.ToInt32(element.Elements("ProductId") .Select(elt =&gt; elt.Value) .SingleOrDefault()); </code></pre> <p>(due to the way that <code>Convert.ToInt32</code> returns 0 when passed a null argument.)</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