Today we discuss few things about the aggregation function of lamda concepts.
Lets start our discussion with an example.
Consider we have string of array with countries name which must be converted in to single string as done using aggregation function with lamda expression.
To understand better we first accomplish the above task using traditional coding style later do it with lamda expression aggregation function.
Below is the code where stores countries strings in countries variable then took foreach iteration and appended strings with comma but with this we observe that at last comma (,) got appended as shown in its output after Germany string.
In order to remove comma(,) from last string i.e after Germany we used strings built-in function named LastIndexOf This function returns integer value which is position of last character in string. In our case last character is comma(,) which we provided as parameter to this function and its position is returned to lastindex variable which passed to result string variable and applied remove function and now we got the expected string as shown below.
Now you can see that there is no comma (,) after the Germany string as shown below.
The same task can be accomplished with aggregate function using lamda expression.
We use aggregate function on Countries string array variable and provide lamda expression with two parameters a,b and provide expected concatenation output as shown below:
Whose output can be as expected.
Hence it reduces the lines of code and makes life easy.
Technically it accepts at first India and US as parameter a and b then makes string as quoted in lamda expression India,US as single string then considers India,US as parameter a and b as France and process as per expression and concatenates as single string as India,US,France and so on.
This can be elaborated as tabular format
As you can see that finally we got the desired string. Single line with aggregate accomplishes multiple lines of code as seen in first example of this blog.
That’s all for the day.
Happy Programming…. 🙂