본문 바로가기

.NET/C# Basic

Array.Find / List.Find Method 사용 예

반응형


List.Find Method

Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List.

Namespace: System.Collections.Generic
Assembly: mscorlib (in mscorlib.dll)



C#
public T Find (
    Predicate<T> match
)

using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>();

        dinosaurs.Add("Compsognathus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Oviraptor");
        dinosaurs.Add("Velociraptor");
        dinosaurs.Add("Deinonychus");
        dinosaurs.Add("Dilophosaurus");
        dinosaurs.Add("Gallimimus");
        dinosaurs.Add("Triceratops");

        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nTrueForAll(EndsWithSaurus): {0}",
            dinosaurs.TrueForAll(EndsWithSaurus));

        Console.WriteLine("\nFind(EndsWithSaurus): {0}", 
            dinosaurs.Find(EndsWithSaurus));

        Console.WriteLine("\nFindLast(EndsWithSaurus): {0}",
            dinosaurs.FindLast(EndsWithSaurus));

        Console.WriteLine("\nFindAll(EndsWithSaurus):");
        List<string> sublist = dinosaurs.FindAll(EndsWithSaurus);

        foreach(string dinosaur in sublist)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
            "\n{0} elements removed by RemoveAll(EndsWithSaurus).", 
            dinosaurs.RemoveAll(EndsWithSaurus));

        Console.WriteLine("\nList now contains:");
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nExists(EndsWithSaurus): {0}", 
            dinosaurs.Exists(EndsWithSaurus));
    }

    // Search predicate returns true if a string ends in "saurus".
    private static bool EndsWithSaurus(String s)
    {
        if ((s.Length > 5) && 
            (s.Substring(s.Length - 6).ToLower() == "saurus"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}


Array.Find 제네릭 메서드 

참고: 이 메서드는 .NET Framework 버전 2.0에서 새로 추가되었습니다.

지정한 조건자에 정의된 조건과 일치하는 요소를 검색하여 전체 Array에서 일치하는 첫 번째 요소를 반환합니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

C#
public static T Find<T> (
    T[] array,
    Predicate<T> match
)

C#
using System;
using System.Drawing;

public class Example
{
    public static void Main()
    {
        // Create an array of five Point structures.
        Point[] points = { new Point(100, 200), 
            new Point(150, 250), new Point(250, 375), 
            new Point(275, 395), new Point(295, 450) };

        // To find the first Point structure for which X times Y 
        // is greater than 100000, pass the array and a delegate
        // that represents the ProductGT10 method to the Shared 
        // Find method of the Array class. 
        Point first = Array.Find(points, ProductGT10);

        // Note that you do not need to create the delegate 
        // explicitly, or to specify the type parameter of the 
        // generic method, because the C# compiler has enough
        // context to determine that information for you.

        // Display the first structure found.
        Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
    }

    // This method implements the test condition for the Find
    // method.
    private static bool ProductGT10(Point p)
    {
        if (p.X * p.Y > 100000)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

/* This code example produces the following output:

Found: X = 275, Y = 395
 */





기타 응용법 

//DateTime dt = Array.Find<DateTime>( yourDateTimeArray, 
//delegate(DateTime obj) {
//   return obj == new DateTime(2005, 4, 23, 8, 30, 0);
//}
//);

기타 응용법 2

    private static int tempListValue = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
      
        List<int> list1 = CommonClass.CommonCodeGet.GroupCode();
        DataSet ds = CommonClass.CommonCodeGet.GetNameAndGroupCodeToMemeberId(Page.User.Identity.Name);
        Label1.Text = Page.User.Identity.Name;
        Label2.Text = ds.Tables[0].Rows[0]["MEM_NM"].ToString();

        tempListValue = Convert.ToInt32(ds.Tables[0].Rows[0]["Group_CD"]);

        int? boolValue = list1.Find(EndsWithSaurus);

         if (tempListValue == boolValue)
        {
            (CommonClass.FindControlRecursive(this.Page.Master.FindControl("Userinfo1"), "btnCafeButton") as Button).Visible = true;
        }