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

  • 作成日 2021.07.26
  • 更新日 2022.04.12
  • C#
C# 配列またはリストの先頭の値を取得する

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

環境

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

配列またはリストの先頭の値を取得

配列またはリストの先頭の値を取得するには、Linqの「First」を使用することで可能です。

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

// 先頭の値を取得
num.First();

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

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

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            // Listを用意
            var list = new List<int> { 1, 2, 3, 4, 5 };

            Console.WriteLine(list.First());

            System.Console.ReadKey();

        }
    }
}

実行結果

以下のように、条件を設定して取得することも可能です。

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

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {

            // Listを用意
            var list = new List<int> { 1, 2, 3, 4, 5 };

            Console.WriteLine(list.First(v => v %2 == 0));

            System.Console.ReadKey();

        }
    }
}

実行結果