C# List(リスト)の指定した値のインデックス番号を取得する

  • 作成日 2020.12.16
  • 更新日 2022.03.04
  • C#
C# List(リスト)の指定した値のインデックス番号を取得する

C#で、List(リスト)内にある値から、IndexOfを使用して、インデックス番号を取得するサンプルコードを記述してます。

環境

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

IndexOf使い方

IndexOfを使用すると、指定した値のインデックス番号を取得することが可能です。

ここでは、作成したListの、値「one,two,three」のインデックス番号を取得してます。

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

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

            var list = new List<string> { "one", "two", "three", "four", "five" };

            // 結果
            Console.WriteLine(list.IndexOf("one")); // 0
            Console.WriteLine(list.IndexOf("two")); // 1
            Console.WriteLine(list.IndexOf("three")); // 2
        }
    }
}