Friday, 2 June 2017

LINQ 10 Function chaining

Linq is based on aggregating functions, that is chaining them together.

using System;
using System.Linq;

namespace LINQ04
{
    class Program
    {
        static void Main(string[] args)
        {
            var nums = Enumerable.Range(0, 20);

            //Count
            int EvenCount = nums.Where(n => n % 2 == 0).Count();
            Console.WriteLine($"There are {EvenCount} even Numbers");

            //Average
            double numAVG = nums.Average();
            Console.WriteLine($"The average number is {numAVG}");

            //Sum
            double OddSum = nums.Where(n => n % 2 == 1).Sum();
            Console.WriteLine($"Sum odd numbers is {OddSum}");

            //Min
            double EvenMin = nums.Where(n => n % 2 == 0).Min();
            Console.WriteLine($"smallest Even numbers is {EvenMin}");

            //Max
            double OddLarge = nums.Where(n => n % 2 == 1).Max();
            Console.WriteLine($"Largets odd numbers is {OddLarge}");

            //first
            double firstOdd = nums.Where(n => n % 2 == 1).First();
            Console.WriteLine($"First odd numbers is {firstOdd}");

            //last
            double lastOdd = nums.Where(n => n % 2 == 1).Last();
            Console.WriteLine($"Last Multiple of 3 is {lastOdd}");
        }
    }

}

Linq has numerous functions that can be used to find information about your collections like Max or sum.