Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression to return zero if null

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

  1. need to return the value as int

  2. if the canvas contains no controls it will raise error (tried using Nullable type, but failed)

like image 929
Binil Avatar asked Dec 22 '22 19:12

Binil


1 Answers

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.

like image 72
Lee Avatar answered Jan 06 '23 09:01

Lee