Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since Max() requires at least one element in its sequence you either have to </p> <ul> <li>catch the exception and set max to zero</li> <li>check the length before calling Max(). <em>I'd recommend this</em></li> </ul> <p>While it is possible to write the logic in one long query expression, I'd recommend you break it up a bit to improve readability. Create a method that returns the integer part of a child control's name:</p> <pre><code>private int NumberFromElementName(string name) { // Or search for the last '_' using name.LastIndexOf() var numString = name.Substring("Control_".Length); return Int32.Parse(numString); } </code></pre> <p>Then do the query in two steps to allow you to look at the length of the returned sequence. Notice I convert it to an array to avoid having to run the query twice. I'm also using the <a href="http://msdn.microsoft.com/en-us/library/bb360913.aspx" rel="nofollow">OfType</a> extension method so that it works even if the canvas has a child which isn't of type FrameworkElement.</p> <pre><code>var children = canvas1.Children.OfType&lt;FrameworkElement&gt;().ToArray(); int max = 0; if (children.Length &gt; 0) max = children.Max(x =&gt; NumberFromElementName(x.Name)); string nextChildName = String.Format ("Control_{0}", max + 1); </code></pre> <p><strong>EDIT:</strong> As pointed out by @Jan in his answer, you can avoid splitting the query in two parts by using the <a href="http://msdn.microsoft.com/en-us/library/bb355419.aspx" rel="nofollow">DefaultIfEmpty</a> before the Max call in the query.</p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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