Csharp/C Sharp/LINQ/Aggregate
Содержание
Aggregate and Sum
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {
public static void Main() { IEnumerable<int> intSequence = Enumerable.Range(1, 10); foreach (int item in intSequence) Console.WriteLine(item); int sum = intSequence.Aggregate(0, (s, i) => s + i); Console.WriteLine(sum); }
}
</source>
Aggregate Prototype
<source lang="csharp"> using System; using System.Linq; using System.Collections; using System.Collections.Generic; public class MainClass {
public static void Main() { int N = 5; IEnumerable<int> intSequence = Enumerable.Range(1, N); foreach (int item in intSequence) Console.WriteLine(item); int agg = intSequence.Aggregate((av, e) => av * e); Console.WriteLine("{0}! = {1}", N, agg); }
}
</source>
Use Aggregate on an array
<source lang="csharp">
using System; 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); }
}
</source>
Use Aggregate on an array with tenary operator
<source lang="csharp"> using System; 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)); }
}
</source>