C#/C#200제

[C#] 17일차 - 119. List<T>에서 Predicate<T>델리게이트 사용

반나무 2021. 2. 15. 19:04
리턴 타입 원형 설명
bool List<T>.Exists(Predicate<T>) 조건에 맞는 요소가 있는지
T List<T>.Find(Predicate<T>) 조건에 맞는 첫 번째 요소 리턴
List<T> List<T>.FindAll(Predicate<T>) 조건에 맞는 모든 요소 리턴
T List<T>.FindLast(Predicate<T>) 조건에 맞는 마지막 요소 리턴
int List<T>.RemoveAll(Predicate<T>) 조건에 맞는 요소를 모두 제거
bool List<T>.TrueForAll(Predicate<T>) 모든 요소가 조건에 맞는지

여기서 Predicate<T>는 보통 람다식으로 표현된다.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A119_ListAndLambda
{
    class Program
    {
        static void Main(string[] args)
        {
            List<String> myList = new List<String>
            {
                "mouse", "cow", "tiger", "rabbit", "dragon", "snake"
            };

            bool n = myList.Exists(s => s.Contains("x"));
            Console.WriteLine("이름에 'x'를 포함하는 동물이 있나요: " + n);

            Console.Write("이름이 3글자인 첫 번째 동물 :");
            string name = myList.Find(s => s.Length == 3);
            Console.WriteLine(name);

            Console.Write("이름이 6글자 이상인 동물들 : ");
            List<string> longName = myList.FindAll(s => s.Length > 5);
            foreach (var item in longName)
                Console.Write(" {0}", item);
            Console.WriteLine();

            Console.Write("대문자로 변환 : ");
            List<string> capList = myList.ConvertAll(s => s.ToUpper());
            foreach (var item in capList)
                Console.Write(" {0}", item);
            Console.WriteLine();
        }
    }
}

반응형