Enumerable Method Series : Enumerable.Aggregate

int[] a = { 1, 2, 4, 5, 6, 7, 8, 9, 10 };

Method #1
int b = a.Aggregate((x, y) => x += y); // Simple Aggregate (Result : 52)
//Alternative or Interpretation
//
for (int i = 0; i <= a.GetUpperBound(0); i++)
x += a[i];
int b = x;

Method #2

int c = a.Aggregate(0, (x, y) => x += y); // Initialize with value(0) before
aggregate process start (Result : 52)


//Alternative or Interpretation
//
int x = 0;
for (int i = 0; i <= a.GetUpperBound(0); i++) x += a[i]; int c = x;

Method #3
int d = a.Aggregate(0, (x, y) => x += y, z => z >= 1 ? z : 0);
// Initialize with value(0) before aggregate process start
// After aggregate process done final result will move to

// another section for further process on final result.
// Like here if result is greater than 0, it will return aggregated result else 0

//Alternative or Interpretation
//
int x = 0;
for (int i = 0; i <= a.GetUpperBound(0); i++)
x += a[i];
int c = x >=1 ? x: 0;

Comments

Popular posts from this blog

Difference between Parse/TryParse/ParseExact/TryParseExact

Benefits of Test Driven Development (TDD)

Version history of C#