Unity/TIL

C# List<T> Find, FindIndex

김차루 2024. 4. 30. 23:10
스파르타 내배캠 12일차 TIL
C2조_💖 코딩(인줄 알았지 하드코딩 이지롱)

 

 

 

사과 맛있겠다, 청송 사과 맛있지, 뉴진스최고야 뉴진스잘한다 뉴진스예쁘다 

   

 

    밖에 안 남은 클래스 튜터링은 강의 정리할 때 내용을 이어서 정리 해보고 오늘은 팀프로젝트를 진행하면서 유용하게 사용했던 메서드를 정리 해보려고 한다. 아무래도 아이템 리스트를 건드리는 작업이 많다보니 list를 탐색할 필요가 있었다. 그래서 검색을 했고 아래의 링크를 참고하여 구현했다.

https://dragontory.tistory.com/545

 

C# List<T> Find , FindIndex , FindAll , FindLast | C# 강좌

C# List Find , FindIndex , FindAll , FindLast | C# 강좌 C#에서 List 클래스는 목록에서 지정된 조건과 일치하는 요소를 검색하는 데 사용할 수 있는 Find 메서드를 제공합니다. List.Find : Find 메서드의 형식은

dragontory.tistory.com

 

    List<T>.Find : 목록에서 지정된 조건과 일치하는 요소를 검색하는 데 사용할 수 있다.

public T Find(Predicate<T> match)

//예시
static void main()
{
	List<int> numbers = new List<int> {1, 2, 3, 4, 5};
    
    int foundNumber = numbers.Find(n => n == 3);
    
    Console.WriteLine(founNumber);
}

 

    Find 메서드를 호출하고 람다 식을 인수로 전달한다. (n => n==3)인 람다식은 요소가 3인 경우를 검색 하라는 것이다. Find 메서드는 목록에서 이 조건 충족하는 첫 번째 요소를 반환한다. 만약, 검색 결과 일치하는 요소가 없다면 Find메서드는 0의 값을 리턴한다. 

 

    List<T>.FindIndex : List 요소 중에 조건에 일치하는 요소가 있을 경우 해당 인덱스를 리턴한다.

static void main()
{
	List<string> fruits = new List<string> {"apple", "banana", "cherry", "date", "elderberry"};
    
    int index = fruits.FindIndex(f => f.StartsWith("c"));
    
    if(index == -1)
    {
    	Console.WriteLine("No fruit starting with 'c' found");
    }
    else
    {
    	Console.WriteLine(fruits[index]); //Out: cherry
    }
}

 

    FindIndex 같은 경우, 일치하는 요소가 없을 경우에는 -1을 반환한다. 

프로젝트 중

    프로젝트에서는 item 종류 중 물약을 찾기 위해 사용했다. 

 

    List<T>.FindAll : match에 지정된 조건과 일치하는 모든 요소를 반환한다.

static void Main()
    {
        List<int> numbers = new List<int> { 1, 3, 5, 7, 9 };

        List<int> greaterThan5 = numbers.FindAll(n => n > 5);

        foreach (int number in greaterThan5)
        {
            Console.WriteLine(number); // Output: 7 9
        }
    }

 

    예제 코드에서는 List<int>였지만 list 전문도 가능하다. 목록의 요소가 조건을 충족하지 않으면 FindAll 메서드는 빈 List을 반환한다. 

 

List<T>.FindLast : 지정된 조건을 만족하는 목록의 마지막 요소를 반환한다.

static void Main()
    {
        List<int> numbers = new List<int> { 1, 3, 5, 7, 8, 9, 10 };

        int lastEvenNumber = numbers.FindLast(n => n % 2 == 0);

        if (lastEvenNumber == 0)
        {
            Console.WriteLine("No even number found");
        }
        else
        {
            Console.WriteLine(lastEvenNumber); // Output: 10
        }
    }

 

    FindLast 메서드가 일치 매개 변수에 지정된 조건을 충족하는 요소를 목록에서 찾지 못한 경우 목록의 요소 유형에 대한 기본값을 반환한다. int와 같은 값 유형의 경우 기본값은 0이다. 참조의 경우 null값이다.