Aggregate
In this chapter you will learn:
- How to use Aggregate operator
- Use Aggregate to calculate product
- Use Aggregate on an array with tenary operator
Get to know Aggregate
Aggregate
accepts custom accumulation algorithm for implementing aggregations.
The following demonstrates how Aggregate
can do the work of Sum:
using System;// j ava2s . c o m
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
public class MainClass{
public static void Main(string[] args){
int[] intArray = { 1, 2, 3, 4, 5 };
var result =intArray.Aggregate((ThisElement, Next) => ThisElement + Next);
Console.WriteLine(result);
}
}
Aggregate with product
using System;// j a va 2 s. c o m
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass {
public static void Main() {
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var query = numbers.Aggregate((a, b) => a * b);
}
}
Aggregate with tenary operator
using System;// j a v a 2 s . c o m
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
public class MainClass{
public static void Main(){
int[] numbers = { 9, 3, 5, 4, 2, 6, 7, 1, 8 };
var query = numbers.Aggregate(5, (a,b) => ( (a < b) ? (a * b) : a));
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Linq Operators