Since Max () requires at least one element in its sequence, you must either
- catch the exception and set max to zero
- check the length before calling Max (). I would recommend this
Although you can write the logic in one long query expression, I would recommend that you figure it out a bit to improve readability. Create a method that returns the integer part of the child control:
private int NumberFromElementName(string name) {
Then complete the query in two steps so that you can see the length of the returned sequence. Note that I convert it to an array to avoid having to run the query twice. I also use the OfType extension method to make it work even if there is a child in the canvas that is not of type FrameworkElement.
var children = canvas1.Children.OfType<FrameworkElement>().ToArray(); int max = 0; if (children.Length > 0) max = children.Max(x => NumberFromElementName(x.Name)); string nextChildName = String.Format ("Control_{0}", max + 1);
EDIT: As @Jan noted in his answer, you can avoid splitting the request in two parts by using DefaultIfEmpty before calling Max in the request.
source share