どうも、ちょげ(@chogetarou)です。
List(リスト)を条件で検索して、条件に合致する要素のインデックスを取得する方法を紹介します。
方法

Listを条件で検索してインデックスを取得するには、FindIndex()メソッドを使います。
まず、ListからFindIndex()メソッドを呼び出します。
FindIndex()メソッドの引数に、引数を1つ持つラムダ式を指定します。
そして、FindIndex()メソッドの引数のラムダ式で条件式を返します。
list.FindIndex(item => 条件式);
FindIndex()メソッドは、ラムダ式の条件式で要素を検索して、条件式で最初にTrueを返した要素のインデックスを返します。
使用例
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var index1 = numbers.FindIndex(item => item == 3);
var index2 = numbers.FindIndex(item => item % 2 == 0);
Console.WriteLine(index1); //2
Console.WriteLine(index2); //1
}
}
コメント