C#
C# List<T> FindIndex 사용법
DragonTory
2023. 1. 18. 22:44
반응형
C# List<T> FindIndex 사용법
List를 사용 하여 목록을 사용 할 때
특정 값에 일치 하는 아이템의 인덱스( 0부터 시작 아이디)를 리턴 해주는 메소드 입니다.
메소드:
public int FindIndex (Predicate<T> match);
public int FindIndex (int startIndex, Predicate<T> match);
public int FindIndex (int startIndex, int count, Predicate<T> match);
리턴값:
성공 ) 찾는 항목이 있을 경우 0보다 큰 인덱스 값.
실패) 없을 경우 -1 값을 리턴
예제)
Unity C#
int index = itemList.FindIndex(x => x.name.Equals(itemName) );
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindIndex : MonoBehaviour
{
class Item
{
public string name;
public int value;
public Item(string name, int value)
{
this.name = name;
this.value = value;
}
}
List<Item> itemList = new ();
void Start()
{
itemList.Add(new ("gold", 300) );
itemList.Add(new ("silver", 200) );
itemList.Add(new ("stone", 100) );
var myItem = FindItem("silver");
if (myItem != null)
{
print($"find result : {myItem.name} value {myItem.value}");
}
}
Item FindItem(string itemName)
{
int index = itemList.FindIndex(x => x.name.Equals(itemName) );
if( index < 0 )
{
return null;
}
return itemList[index];
}
}
|
cs |
출력
반응형