Suppose we have the following integer array in C#:
int[] array = { 5, 1, -4, 0, 5, -8, 5, -3 };
Our aim is to perform a conditional sum of the values of the list excluding a subset of values that satisfy a condition, i.e. negative or positive values.
We can do this using:
double sumOfElem = array.Sum(element => (element < 0 ? 0 : element));
This code uses an overload of Sum
that utilizes a transform function (so called selector),
which is applied to each element of the array.
The above selector filters out negative elements. To filter out positive ones, we can simply inverse the comparison operator:
double sumOfElem = array.Sum(element => (element > 0 ? 0 : element));
No comments:
Post a Comment