C#에서 List<T> 컬렉션 안에서 지정한 조건과 일치하는 요소를 검색하고, 그 요소가 마지막으로 나타나는 위치의 0부터 시작하는 인덱스를 얻으려면 FindLastIndex() 메서드를 사용하면 됩니다.
FindLastIndex() 메서드란?
FindLastIndex()는 Predicate<T> 형태의 조건식을 받아 목록의 끝에서부터 역방향으로 요소를 검색한 뒤, 조건을 만족하는 마지막 요소의 0 기반 인덱스를 반환합니다. 만약 조건을 만족하는 요소가 하나도 없다면 -1을 반환합니다.
예제 1
다음은 조건에 맞는 요소를 검색해 전체 목록에서 마지막으로 나타나는 인덱스를 반환하는 코드입니다.
using System;
using System.Collections.Generic;
public class Demo {
private static bool demo(int i) {
return ((i % 10) == 0);
}
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(200);
list.Add(215);
list.Add(310);
list.Add(500);
list.Add(600);
Console.WriteLine("List elements...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine("Last Index of the satisfying condition = "+list.FindLastIndex(demo));
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
List elements... 200 215 310 500 600 Last Index of the satisfying condition = 4
이 예제에서 조건은 “10으로 나누어 떨어지는 수”입니다. 목록의 끝에서부터 검색했을 때 가장 마지막으로 조건을 만족하는 요소는 600이며, 해당 요소의 인덱스인 4가 반환됩니다.
예제 2
이번에는 또 다른 예제를 살펴보겠습니다.
using System;
using System.Collections.Generic;
public class Demo {
private static bool demo(int i) {
return ((i % 2) == 0);
}
public static void Main(String[] args) {
List<int> list = new List<int>();
list.Add(200);
list.Add(215);
list.Add(310);
list.Add(500);
list.Add(655);
Console.WriteLine("List elements...");
foreach (int i in list) {
Console.WriteLine(i);
}
Console.WriteLine("Last Index of the satisfying condition = "+list.FindLastIndex(demo));
}
}출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
List elements... 200 215 310 500 655 Last Index of the satisfying condition = 3
이번 예제의 조건은 “짝수”입니다. 목록의 마지막 요소인 655는 홀수라서 조건을 만족하지 않으며, 그 앞에 있는 500이 짝수이므로 인덱스 3이 최종 결과로 반환됩니다.