計算機科学のブログ

LINQ and lambdas - Get Control of your data - Enumerable, Range, Sum, Average, Min, Max, Count, Last, Skip, Reverse, Last

Head First C#: A Learner’s Guide to Real-World Programming with C# and .NET Core (Andrew Stellman(著)、Jennifer Greene(著)、O’Reilly Media)のChapter 9(LINQ and lambdas - Get Control of your data)、p.473(Sharpen your pencil)の解答を求めてみる。

コード

using System;
using System.Collections.Generic;
using System.Linq;

namespace TwoDecksBlazor
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> vs = new List<int>()
            {
                Enumerable.Range(1, 5).Sum(),
                new int[]{3, 7, 9, 1, 10, 2, -3 }.Min(),
                new int[] {8, 6, 7, 5, 3, 0, 9 }.Max(),
                Enumerable.Range(10, 3721).Count(),
                Enumerable.Range(5, 100).Last(),
                new List<int>() {3, 8, 7, 6, 9, 6, 2 }
                .Skip(4)
                .Sum(),
                Enumerable.Range(10, 731)
                .Reverse()
                .Last(),
            };
            List<int> vs1 = new List<int>()
            {
                15,
                -3,
                9,
                3721,
                104,
                17,
                10,
            };
            for (int i = 0; i < vs.Count; i++)
            {
                Console.WriteLine(vs[i] == vs1[i]);
            }
            Console.WriteLine(
                Enumerable.Range(1, 6).Average() == 3.5
                );
        }
    }
}

入出力結果(Terminal, Zsh)

True
True
True
True
True
True
True
True