in my WPF application i used to add controls dynamically to a Canvas. The name format of the control is "Control_UniqueValue".
i.e., if i add first control to the canvas, then the name will be "Control_1" and the next will be "Control_2" etc...
my requirement is to get the max value of the added controls
i used the following statement for that
string maxId = (string)canvas1.Children.Cast<FrameworkElement>().ToList().Max(x => (x.Name.Substring(x.Name.LastIndexOf('_') + 1)));
but the problem here is
need to return the value as int
if the canvas contains no controls it will raise error (tried using Nullable
type, but failed)
int maxId = canvas1.Children
.Cast<FrameworkElement>()
.Select(e => int.Parse(e.Name.Substring(e.Name.LastIndexOf('_'))))
.DefaultIfEmpty()
.Max();
This should return 0 instead of throwing an exception if there are no elements in the sequence. Also, the call to ToList
in your code is not required. This will still throw an exception if any of the control names are not in the expected format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With