Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

List<T>.FindIndex Method (Int32, Int32, Predicate<T>)

Searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the range of elements in the List<T> that starts at the specified index and contains the specified number of elements.

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

public int FindIndex(
	int startIndex,
	int count,
	Predicate<T> match
)

Parameters

startIndex
Type: System.Int32

The zero-based starting index of the search.

count
Type: System.Int32

The number of elements in the section to search.

match
Type: System.Predicate<T>

The Predicate<T> delegate that defines the conditions of the element to search for.

Return Value

Type: System.Int32
The zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.

ExceptionCondition
ArgumentNullException

match is null.

ArgumentOutOfRangeException

startIndex is outside the range of valid indexes for the List<T>.

-or-

count is less than 0.

-or-

startIndex and count do not specify a valid section in the List<T>.

The List<T> is searched forward starting at startIndex and ending at startIndex plus count minus 1, if count is greater than 0.

The Predicate<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<T> are individually passed to the Predicate<T> delegate.

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

The following example demonstrates the find methods for the List<T> class. The example for the List<T> class contains book objects, of class Book, using the data from the Sample XML File: Books (LINQ to XML). The FillList method in the example uses LINQ to XML [from BPUEDev11] 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<T>)

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

C# example uses an anonymous delegate.

FindAll(Predicate<T>)

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

FindLast(Predicate<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<T>)

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

FindLastIndex(Predicate<T>)

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

FindIndex(Int32, Int32, Predicate<T>)

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

FindLastIndex(Int32, Int32, Predicate<T>)

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace Find
{
    class Program
    {
        private static string IDtoFind = "bk109";

        private static List<Book> Books = new List<Book>();
        public static void Main(string[] args)
        {
            FillList();

            // Find a book by its ID.
            Book result = Books.Find(
            delegate(Book bk)
            {
                return bk.ID == IDtoFind;
            }
            );
            if (result != null)
            {
                DisplayResult(result, "Find by ID: " + IDtoFind);   
            }
            else
            {
                Console.WriteLine("\nNot found: {0}", IDtoFind);
            }


            // Find last book in collection published before 2001.
            result = Books.FindLast(
            delegate(Book bk)
            {
                DateTime year2001 = new DateTime(2001,01,01);
                return bk.Publish_date < year2001;
            });
            if (result != null)
            {
                DisplayResult(result, "Last book in collection published before 2001:");
            }
            else
            {
                Console.WriteLine("\nNot found: {0}", IDtoFind);
            }


            // Find all computer books.
            List<Book> results = Books.FindAll(FindComputer);
            if (results.Count != 0)
            {
                DisplayResults(results, "All computer:");
            }
            else
            {
                Console.WriteLine("\nNo books found.");
            }

            // Find all books under $10.00.
            results = Books.FindAll(
            delegate(Book bk)
            {
                return bk.Price < 10.00;
            }
            );
            if (results.Count != 0)
            {
                DisplayResults(results, "Books under $10:");
            }
            else
            {
                Console.WriteLine("\nNo books found.");
            }


            // Find index values.
            Console.WriteLine();
            int ndx = Books.FindIndex(FindComputer);
            Console.WriteLine("Index of first computer book: {0}", ndx);
            ndx = Books.FindLastIndex(FindComputer);
            Console.WriteLine("Index of last computer book: {0}", ndx);

            int mid = Books.Count / 2;
            ndx = Books.FindIndex(mid, mid, FindComputer);
            Console.WriteLine("Index of first computer book in the second half of the collection: {0}", ndx);

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

        }





        // Populates the list with sample data. 
        private static void FillList()
        {

            // Create XML elements from a source file.
            XElement xTree = XElement.Load(@"c:\temp\books.xml");

            // Create an enumerable collection of the elements.
            IEnumerable<XElement> elements = xTree.Elements();

            // Evaluate each element and set set values in the book object. 
            foreach (XElement el in elements)
            {
                Book book = new Book();
                book.ID = el.Attribute("id").Value;
                IEnumerable<XElement> props = el.Elements();
                foreach (XElement p in props)
                {


                    if (p.Name.ToString().ToLower() == "author")
                    {
                        book.Author = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "title")
                    {
                        book.Title = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "genre")
                    {
                        book.Genre = p.Value;
                    }
                    else if (p.Name.ToString().ToLower() == "price")
                    {
                        book.Price = Convert.ToDouble(p.Value);
                    }
                    else if (p.Name.ToString().ToLower() == "publish_date")
                    {
                        book.Publish_date = Convert.ToDateTime(p.Value);
                    }
                    else if (p.Name.ToString().ToLower() == "description")
                    {
                        book.Description = p.Value;
                    }
                }

                Books.Add(book);

            }

            DisplayResults(Books, "All books:");

        }

        // Explicit predicate delegate. 
        private static bool FindComputer(Book bk)
        {

            if (bk.Genre == "Computer")
            {
                return true;
            }
	    else
            {
                return false;
            }

        }

        private static void DisplayResult(Book result, string title)
        {
            Console.WriteLine();
            Console.WriteLine(title);
            Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", result.ID,
                result.Author, result.Title, result.Genre, result.Price,
                result.Publish_date.ToShortDateString());
            Console.WriteLine();


        }

        private static void DisplayResults(List<Book> results, string title)
        {
            Console.WriteLine();
            Console.WriteLine(title);
            foreach (Book b in results)
            {

                Console.Write("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}", b.ID,
                    b.Author, b.Title, b.Genre, b.Price,
                    b.Publish_date.ToShortDateString());
            }
            Console.WriteLine();

        }

    }

    public class Book
    {
        public string ID { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
        public string Genre { get; set; }
        public double Price { get; set; }
        public DateTime Publish_date { get; set; }
        public string Description { get; set; }
    }
}

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft