다음을 통해 공유


List<T>.Exists(Predicate<T>) 메서드

정의

지정된 조건자에 정의된 조건과 일치하는 요소가 List<T>에 포함되어 있는지 여부를 확인합니다.

public:
 bool Exists(Predicate<T> ^ match);
public bool Exists (Predicate<T> match);
member this.Exists : Predicate<'T> -> bool
Public Function Exists (match As Predicate(Of T)) As Boolean

매개 변수

match
Predicate<T>

검색할 요소의 조건을 정의하는 Predicate<T> 대리자입니다.

반환

지정된 조건자에 정의된 조건과 일치하는 요소가 하나 이상 List<T>에 포함되어 있으면 true이고, 그렇지 않으면 false입니다.

예외

match이(가) null인 경우

예제

다음 예제에서는 Contains 구현 하는 간단한 비즈니스 개체를 포함 하는 의 및 Exists 메서드 List<T> 를 보여 줍니다.Equals

using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify a part
// but the part name can change.
public class Part : IEquatable<Part>
{
    public string PartName { get; set; }
    public int PartId { get; set; }

    public override string ToString()
    {
        return "ID: " + PartId + "   Name: " + PartName;
    }
    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        Part objAsPart = obj as Part;
        if (objAsPart == null) return false;
        else return Equals(objAsPart);
    }
    public override int GetHashCode()
    {
        return PartId;
    }
    public bool Equals(Part other)
    {
        if (other == null) return false;
        return (this.PartId.Equals(other.PartId));
    }
    // Should also override == and != operators.
}
public class Example
{
    public static void Main()
    {
        // Create a list of parts.
        List<Part> parts = new List<Part>();

        // Add parts to the list.
        parts.Add(new Part() { PartName = "crank arm", PartId = 1234 });
        parts.Add(new Part() { PartName = "chain ring", PartId = 1334 });
        parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
        parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
        parts.Add(new Part() { PartName = "cassette", PartId = 1534 });
        parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;

        // Write out the parts in the list. This will call the overridden ToString method
        // in the Part class.
        Console.WriteLine();
        foreach (Part aPart in parts)
        {
            Console.WriteLine(aPart);
        }

        // Check the list for part #1734. This calls the IEquatable.Equals method
        // of the Part class, which checks the PartId for equality.
        Console.WriteLine("\nContains: Part with Id=1734: {0}",
            parts.Contains(new Part { PartId = 1734, PartName = "" }));

        // Find items where name contains "seat".
        Console.WriteLine("\nFind: Part where name contains \"seat\": {0}",
            parts.Find(x => x.PartName.Contains("seat")));

        // Check if an item with Id 1444 exists.
        Console.WriteLine("\nExists: Part with Id=1444: {0}",
            parts.Exists(x => x.PartId == 1444));

        /*This code example produces the following output:

        ID: 1234   Name: crank arm
        ID: 1334   Name: chain ring
        ID: 1434   Name: regular seat
        ID: 1444   Name: banana seat
        ID: 1534   Name: cassette
        ID: 1634   Name: shift lever

        Contains: Part with Id=1734: False

        Find: Part where name contains "seat": ID: 1434   Name: regular seat

        Exists: Part with Id=1444: True
         */
    }
}
Imports System.Collections.Generic

' Simple business object. A PartId is used to identify a part 
' but the part name can change. 
Public Class Part
    Implements IEquatable(Of Part)
    Public Property PartName() As String
        Get
            Return m_PartName
        End Get
        Set(value As String)
            m_PartName = Value
        End Set
    End Property
    Private m_PartName As String
    Public Property PartId() As Integer
        Get
            Return m_PartId
        End Get
        Set(value As Integer)
            m_PartId = Value
        End Set
    End Property
    Private m_PartId As Integer

    Public Overrides Function ToString() As String
        Return Convert.ToString("ID: " & PartId & "   Name: ") & PartName
    End Function
    Public Overrides Function Equals(obj As Object) As Boolean
        If obj Is Nothing Then
            Return False
        End If
        Dim objAsPart As Part = TryCast(obj, Part)
        If objAsPart Is Nothing Then
            Return False
        Else
            Return Equals(objAsPart)
        End If
    End Function
    Public Overrides Function GetHashCode() As Integer
        Return PartId
    End Function
    Public Overloads Function Equals(other As Part) As Boolean _
        Implements IEquatable(Of Part).Equals
        If other Is Nothing Then
            Return False
        End If
        Return (Me.PartId.Equals(other.PartId))
    End Function
    ' Should also override == and != operators.
End Class
Public Class Example
    Public Shared Sub Main()
        ' Create a list of parts.
        Dim parts As New List(Of Part)()

        ' Add parts to the list.
        parts.Add(New Part() With { _
             .PartName = "crank arm", _
             .PartId = 1234 _
        })
        parts.Add(New Part() With { _
             .PartName = "chain ring", _
             .PartId = 1334 _
        })
        parts.Add(New Part() With { _
             .PartName = "regular seat", _
             .PartId = 1434 _
        })
        parts.Add(New Part() With { _
             .PartName = "banana seat", _
             .PartId = 1444 _
        })
        parts.Add(New Part() With { _
             .PartName = "cassette", _
             .PartId = 1534 _
        })
        parts.Add(New Part() With { _
             .PartName = "shift lever", _
             .PartId = 1634 _
        })



        ' Write out the parts in the list. This will call the overridden ToString method
        ' in the Part class.
        Console.WriteLine()
        For Each aPart As Part In parts
            Console.WriteLine(aPart)
        Next


        ' Check the list for part #1734. This calls the IEquatable.Equals method
        ' of the Part class, which checks the PartId for equality.
        Console.WriteLine(vbLf & "Contains: Part with Id=1734: {0}",
                          parts.Contains(New Part() With { _
             .PartId = 1734, _
             .PartName = "" _
        }))

        ' Find items where name contains "seat".
        Console.WriteLine(vbLf & "Find: Part where name contains ""seat"": {0}",
                          parts.Find(Function(x) x.PartName.Contains("seat")))

        ' Check if an item with Id 1444 exists.
        Console.WriteLine(vbLf & "Exists: Part with Id=1444: {0}",
                          parts.Exists(Function(x) x.PartId = 1444))

        'This code example produces the following output:
        '        
        '        ID: 1234   Name: crank arm
        '        ID: 1334   Name: chain ring
        '        ID: 1434   Name: regular seat
        '        ID: 1444   Name: banana seat
        '        ID: 1534   Name: cassette
        '        ID: 1634   Name: shift lever
        '
        '        Contains: Part with Id=1734: False
        '
        '        Find: Part where name contains "seat": ID: 1434   Name: regular seat
        '
        '        Exists: Part with Id=1444: True 
        '         

    End Sub
End Class

다음 예제에서는 Exists 메서드 및 제네릭 대리자를 사용하는 다른 여러 메서드를 Predicate<T> 보여 줍니다.

List<T> 8개의 공룡 이름을 포함하는 문자열의 1이 생성되며, 그 중 2개(위치 1 및 5)는 "사우루스"로 끝납니다. 이 예제에서는 문자열 매개 변수를 수락하고 입력 문자열이 "saurus"로 끝나는지 여부를 나타내는 부울 값을 반환하는 라는 EndsWithSaurus검색 조건자 메서드도 정의합니다.

, FindLastFindAll 메서드는 Find검색 조건자 메서드를 사용하여 목록을 검색하는 데 사용되며 메서드 RemoveAll 는 "saurus"로 끝나는 모든 항목을 제거하는 데 사용됩니다.

마지막으로 Exists 메서드가 호출 됩니다. 처음부터 목록을 트래버스하여 각 요소를 차례로 메서드로 EndsWithSaurus 전달합니다. 메서드가 모든 요소에 대해 반환되면 검색이 중지되고 메서드가 EndsWithSaurus 반환 truetrue 됩니다. 메서드는 Exists 이러한 모든 요소가 제거되었기 때문에 를 반환 false 합니다.

참고

C# 및 Visual Basic에서는 대리자(Predicate(Of String)Visual Basic의 경우)를 명시적으로 만들 Predicate<string> 필요가 없습니다. 이러한 언어는 컨텍스트에서 올바른 대리자를 유추하고 자동으로 만듭니다.

using namespace System;
using namespace System::Collections::Generic;

// Search predicate returns true if a string ends in "saurus".
bool EndsWithSaurus(String^ s)
{
    return s->ToLower()->EndsWith("saurus");
};

void main()
{
    List<String^>^ dinosaurs = gcnew 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();
    for each(String^ dinosaur in dinosaurs )
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nTrueForAll(EndsWithSaurus): {0}",
        dinosaurs->TrueForAll(gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nFind(EndsWithSaurus): {0}", 
        dinosaurs->Find(gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nFindLast(EndsWithSaurus): {0}",
        dinosaurs->FindLast(gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nFindAll(EndsWithSaurus):");
    List<String^>^ sublist = 
        dinosaurs->FindAll(gcnew Predicate<String^>(EndsWithSaurus));

    for each(String^ dinosaur in sublist)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine(
        "\n{0} elements removed by RemoveAll(EndsWithSaurus).", 
        dinosaurs->RemoveAll(gcnew Predicate<String^>(EndsWithSaurus)));

    Console::WriteLine("\nList now contains:");
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nExists(EndsWithSaurus): {0}", 
        dinosaurs->Exists(gcnew Predicate<String^>(EndsWithSaurus)));
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

TrueForAll(EndsWithSaurus): False

Find(EndsWithSaurus): Amargasaurus

FindLast(EndsWithSaurus): Dilophosaurus

FindAll(EndsWithSaurus):
Amargasaurus
Dilophosaurus

2 elements removed by RemoveAll(EndsWithSaurus).

List now contains:
Compsognathus
Oviraptor
Velociraptor
Deinonychus
Gallimimus
Triceratops

Exists(EndsWithSaurus): False
 */
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)
    {
        return s.ToLower().EndsWith("saurus");
    }
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

TrueForAll(EndsWithSaurus): False

Find(EndsWithSaurus): Amargasaurus

FindLast(EndsWithSaurus): Dilophosaurus

FindAll(EndsWithSaurus):
Amargasaurus
Dilophosaurus

2 elements removed by RemoveAll(EndsWithSaurus).

List now contains:
Compsognathus
Oviraptor
Velociraptor
Deinonychus
Gallimimus
Triceratops

Exists(EndsWithSaurus): False
 */
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs As New List(Of 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()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "TrueForAll(AddressOf EndsWithSaurus: {0}", _
            dinosaurs.TrueForAll(AddressOf EndsWithSaurus))

        Console.WriteLine(vbLf & _
            "Find(AddressOf EndsWithSaurus): {0}", _
            dinosaurs.Find(AddressOf EndsWithSaurus))

        Console.WriteLine(vbLf & _
            "FindLast(AddressOf EndsWithSaurus): {0}", _
            dinosaurs.FindLast(AddressOf EndsWithSaurus))

        Console.WriteLine(vbLf & _
            "FindAll(AddressOf EndsWithSaurus):")
        Dim sublist As List(Of String) = _
            dinosaurs.FindAll(AddressOf EndsWithSaurus)

        For Each dinosaur As String In sublist
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "{0} elements removed by RemoveAll(AddressOf EndsWithSaurus).", _
            dinosaurs.RemoveAll(AddressOf EndsWithSaurus))

        Console.WriteLine(vbLf & "List now contains:")
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "Exists(AddressOf EndsWithSaurus): {0}", _
            dinosaurs.Exists(AddressOf EndsWithSaurus))
        
    End Sub

    ' Search predicate returns true if a string ends in "saurus".
    Private Shared Function EndsWithSaurus(ByVal s As String) _
        As Boolean

        Return s.ToLower().EndsWith("saurus")
    End Function
End Class

' This code example produces the following output:
'
'Compsognathus
'Amargasaurus
'Oviraptor
'Velociraptor
'Deinonychus
'Dilophosaurus
'Gallimimus
'Triceratops
'
'TrueForAll(AddressOf EndsWithSaurus: False
'
'Find(AddressOf EndsWithSaurus): Amargasaurus
'
'FindLast(AddressOf EndsWithSaurus): Dilophosaurus
'
'FindAll(AddressOf EndsWithSaurus):
'Amargasaurus
'Dilophosaurus
'
'2 elements removed by RemoveAll(AddressOf EndsWithSaurus).
'
'List now contains:
'Compsognathus
'Oviraptor
'Velociraptor
'Deinonychus
'Gallimimus
'Triceratops
'
'Exists(AddressOf EndsWithSaurus): False

설명

Predicate<T> 전달된 개체가 대리자에서 정의된 조건과 일치하는 경우 를 반환 true 하는 메서드에 대한 대리자입니다. 현재 List<T> 요소는 대리자에게 Predicate<T> 개별적으로 전달되고 일치 항목이 발견되면 처리가 중지됩니다.

이 메서드는 선형 검색을 수행합니다. 따라서 이 메서드는 O(n) 작업이며 여기서 n 은 입니다 Count.

적용 대상

추가 정보