List<(Of <(T>)>)..::.FindAll Method
This page is specific to:.NET Framework Version:
2.03.03.54
.NET Framework Class Library
List<(Of <(T>)>)..::.FindAll Method

Updated: August 2009

Retrieves all the elements that match the conditions defined by the specified predicate.

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

'Usage

Dim instance As List
Dim match As Predicate(Of T)
Dim returnValue As List(Of T)

returnValue = instance.FindAll(match)

'Declaration

Public Function FindAll ( _
    match As Predicate(Of T) _
) As List(Of T)

Parameters

match
Type: System..::.Predicate<(Of <(T>)>)
The Predicate<(Of <(T>)>) delegate that defines the conditions of the elements to search for.

Return Value

Type: System.Collections.Generic..::.List<(Of <(T>)>)
A List<(Of <(T>)>) containing all the elements that match the conditions defined by the specified predicate, if found; otherwise, an empty List<(Of <(T>)>).
Exceptions

ExceptionCondition
ArgumentNullException

match is nullNothingnullptra null reference (Nothing in Visual Basic).

Remarks

The Predicate<(Of <(T>)>) is a delegate to a method that returns true if the object passed to it matches the conditions defined in the delegate. The elements of the current List<(Of <(T>)>) are individually passed to the Predicate<(Of <(T>)>) delegate, and the elements that match the conditions are saved in the returned List<(Of <(T>)>).

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

Examples

The following example demonstrates the find methods for the List<(Of <(T>)>) class. The example for the List<(Of <(T>)>) class contains book objects, of class Book, using the data from the Sample XML File (books.xml). The FillList method in the example uses LINQ to XML to parse the values from the XML to property values of the book objects.

The following table describes the examples provided for the find methods.

Method

Example

Find(Predicate<(Of <(T>)>))

Finds a book by an ID using the IDToFind predicate delegate.

C# example uses an anonymous delegate.

FindAll(Predicate<(Of <(T>)>))

Find all books that whose Genre property is "Computer" using the FindComputer predicate delegate.

FindLast(Predicate<(Of <(T>)>))

Finds the last book in the collection that has a publish date before 2001, using the PubBefore2001 predicate delegate.

C# example uses an anonymous delegate.

FindIndex(Predicate<(Of <(T>)>))

Finds the index of first computer book using the FindComputer predicate delegate.

FindLastIndex(Predicate<(Of <(T>)>))

Finds the index of the last computer book using the FindComputer predicate delegate.

FindIndex(Int32, Int32, Predicate<(Of <(T>)>))

Finds the index of first computer book in the second half of the collection, using the FindComputer predicate delegate.

FindLastIndex(Int32, Int32, Predicate<(Of <(T>)>))

Finds the index of last computer book in the second half of the collection, using the FindComputer predicate delegate.

Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
Module Module1

    Private IDToFind As String = "bk109"

    Public Books As New List(Of Book)


    Sub Main()

        FillList()

        ' Find a book by its ID.
        Dim result As Book = Books.Find(AddressOf FindID)
        If result IsNot Nothing Then
            DisplayResult(result, "Find by ID: " & IDToFind)
        Else

            Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
        End If
        Console.WriteLine()

        ' Find last book in collection that has a publish date before 2001.
        result = Books.FindLast(AddressOf PubBefore2001)
        If result IsNot Nothing Then
            DisplayResult(result, "Last book in collection published before 2001:")
        Else
            Console.WriteLine(vbCrLf & "Not found: " & IDToFind)
        End If
        Console.WriteLine()

        ' Find all computer books.
        Dim results As List(Of Book) = Books.FindAll(AddressOf FindComputer)
        If results IsNot Nothing Then
            DisplayResults(results, "All computer books:")
        Else
            Console.WriteLine(vbCrLf & "No books found.")
        End If
        Console.WriteLine()


        ' Find all books under $10.00.
        results = Books.FindAll(AddressOf FindUnderTen)
        If results IsNot Nothing Then
            DisplayResults(results, "Books under $10:")
        Else
            Console.WriteLine(vbCrLf & "No books found.")
        End If
        Console.WriteLine()

        ' Find index values.
        Console.WriteLine()
        Dim ndx As Integer = Books.FindIndex(AddressOf FindComputer)
        Console.WriteLine("Index of first computer book: " & ndx)
        ndx = Books.FindLastIndex(AddressOf FindComputer)
        Console.WriteLine("Index of last computer book: " & ndx)

        Dim mid As Integer = Books.Count / 2
        ndx = Books.FindIndex(mid, mid, AddressOf FindComputer)
        Console.WriteLine("Index of first computer book in the second half of the collection: " & ndx)



        ndx = Books.FindLastIndex(Books.Count - 1, mid, AddressOf FindComputer)
        Console.WriteLine("Index of last computer book in the second half of the collection: " & ndx)


    End Sub



    Private Sub FillList()

        ' Create XML elements from a source file.
        Dim xTree As XElement = XElement.Load("c:\temp\books.xml")

        ' Create an enumerable collection of the elements.
        Dim elements As IEnumerable(Of XElement) = xTree.Elements

        ' Evaluate each element and set values in the book object.
        For Each el As XElement In elements
            Dim Book As New Book()
            Book.ID = el.Attribute("id").Value
            Dim props As IEnumerable(Of XElement) = el.Elements
            For Each p As XElement In props
                If p.Name.ToString.ToLower = "author" Then
                    Book.Author = p.Value
                End If
                If p.Name.ToString.ToLower = "title" Then
                    Book.Title = p.Value
                End If
                If p.Name.ToString.ToLower = "genre" Then
                    Book.Genre = p.Value
                End If
                If p.Name.ToString.ToLower = "price" Then
                    Book.Price = Convert.ToDouble(p.Value)
                End If
                If p.Name.ToString.ToLower = "publish_date" Then
                    Book.Publish_date = Convert.ToDateTime(p.Value)
                End If
                If p.Name.ToString.ToLower = "description" Then
                    Book.Description = p.Value
                End If
            Next
            Books.Add(Book)
        Next

        DisplayResults(Books, "All books:")
        Console.WriteLine()

    End Sub

    ' Predicate delegates for
    ' Find and FindAll methods.
    Private Function FindID(ByVal bk As Book) As Boolean
        If bk.ID = IDToFind Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function FindComputer(ByVal bk As Book) As Boolean
        If bk.Genre = "Computer" Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function FindUnderTen(ByVal bk As Book) As Boolean
        Dim tendollars As Double = 10.0
        If bk.Price < tendollars Then
            Return True
        Else
            Return False
        End If
    End Function
    Private Function PubBefore2001(ByVal bk As Book) As Boolean
        Dim year2001 As DateTime = New DateTime(2001, 1, 1)
        Return bk.Publish_date < year2001
    End Function
    Private Sub DisplayResult(ByVal result As Book, ByVal title As String)
        Console.WriteLine()
        Console.WriteLine(title)
        Console.WriteLine(vbLf & result.ID & vbTab & result.Author & _
                          vbTab & result.Title & vbTab & result.Genre & _
                          vbTab & result.Publish_date & vbTab & result.Price)
        Console.WriteLine()
    End Sub
    Private Sub DisplayResults(ByVal results As List(Of Book), ByVal title As String)
        Console.WriteLine()
        Console.WriteLine(title)
        For Each b As Book In results
            Console.Write(vbLf & b.ID & vbTab & b.Author & _
                              vbTab & b.Title & vbTab & b.Genre & _
                              vbTab & b.Publish_date & vbTab & b.Price)
        Next
        Console.WriteLine()
    End Sub

    Public Class Book
        Public ID As String
        Public Author As String
        Public Title As String
        Public Genre As String
        Public Price As Double
        Public Publish_date As DateTime
        Public Description As String
    End Class


End Module


Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 3.5, 3.0, 2.0

.NET Compact Framework

Supported in: 3.5, 2.0

XNA Framework

Supported in: 3.0, 2.0, 1.0
See Also

Reference

Change History

Date

History

Reason

August 2009

Improved example.

Information enhancement.

Community Content

of course if you were really clever...
Added by:tim 123
you could rewrite the EndsWithSaurus function to call String.EndsWith() instead :)
What about the order?
Added by:compadre
Will it return the elements in the order that they were added to the main list?
How hard coded-ly unusable
Added by:booger123

So, by your example, you need to know what your searching for at design time and then write a separate function for each? How nice.

© 2010 Microsoft Corporation. All rights reserved.   Terms of Use | Trademarks | Privacy Statement
Page view tracker
Rate the Lightweight library
x
Lightweight builds on ScriptFree (loband) by adding features you've requested: a SearchBox and default code language selection.
Do you like the SearchBox?
Do you like the tabbed code blocks?
How useful is this topic?
Tell us more.
Thanks
x
You're helping to improve MSDN Online.
Feedback
Switch View
Classic
Lightweight Beta
ScriptFree
Switch View