Csharp/C Sharp/LINQ/Aggregate

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Aggregate and Sum

 
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);
    }
}


Aggregate Prototype

 
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);
    }
}


Use Aggregate on an array

 

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);
    }
}


Use Aggregate on an array with tenary operator

 
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));
    }
}