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

  • 作成日 2022.03.05
  • C#
C# 配列またはリストの合計値を取得する

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

環境

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

合計値を取得

合計値を取得するには、Linqの「Sum」を使用することで可能です。

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

// 合計値を取得
num.Sum(); // 15

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

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
            {
                int reault1 = arr1.Sum();
                int? reault2 = arr2.Sum();
                int reault3 = list.Sum();

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

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

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

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

実行結果