C# 配列またはリストの平均値を取得する

  • 作成日 2021.10.20
  • 更新日 2022.04.09
  • C#
C# 配列またはリストの平均値を取得する

C#で配列またはリストの平均値を取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

平均値を取得

平均値を取得するには、Linqの「Average」を使用することで可能です。

// 配列を用意
int[] num = new int[] { 1, 2, 3, 4, 5 };       

// 平均値を取得
num.Average(); // 3

以下は、配列とリストの平均値を取得して、結果を表示するだけのコードとなります。

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

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr1 = new int[] { 1, 2, 3, 4, 5};
            int?[] arr2 = new int?[] { 1, 2, 3, 4, 5, null };

            List<int> list = new List<int> { 0, 1, 2, 1, 2 };

            try
            {
                double reault1 = arr1.Average();
                double? reault2 = arr2.Average();
                double reault3 = list.Average();

                Console.WriteLine($"実行結果は{reault1}です"); // 3

                Console.WriteLine($"実行結果は{reault2}です"); // 3

                Console.WriteLine($"実行結果は{reault3}です"); // 1.2

            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());             
            }
        }
    }
}

実行結果