List<T>.Find(Predicate<T>) メソッド

定義

指定された述語によって定義された条件と一致する要素を検索し、List<T> 全体の中で最もインデックス番号の小さい要素を返します。

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

パラメーター

match
Predicate<T>

検索する要素の条件を定義する Predicate<T> デリゲート。

戻り値

T

見つかった場合は、指定された述語によって定義された条件と一致する最初の要素。それ以外の場合は、型 T の既定値。

例外

matchnullです。

次の例では、 Find 単純な複合オブジェクトを含む の メソッド List<T> を示します。

C#
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
         */
    }
}

次の例では、 クラスの find メソッドを List<T> 示します。 クラスのList<T>例には、サンプル XML ファイル: Books (LINQ to XML) のデータを使用して、 クラスBookの オブジェクトが含まれていますbook。 この例の メソッドではFillList、LINQ to XMLを使用して、XML の値をオブジェクトのbookプロパティ値に解析します。

次の表に、find メソッドの例を示します。

Method
Find(Predicate<T>) 述語デリゲートを使用して、ID で書籍を IDToFind 検索します。

C# の例では匿名デリゲートを使用します。
FindAll(Predicate<T>) 述語デリゲートを使用して、プロパティが Genre "Computer" であるすべての書籍を FindComputer 検索します。
FindLast(Predicate<T>) 述語デリゲートを使用して、発行日が 2001 より前のコレクション内の最後の書籍を PubBefore2001 検索します。

C# の例では匿名デリゲートを使用します。
FindIndex(Predicate<T>) 述語デリゲートを使用して、最初のコンピューター ブックのインデックスを FindComputer 検索します。
FindLastIndex(Predicate<T>) 述語デリゲートを使用して、最後のコンピューター ブックのインデックスを FindComputer 検索します。
FindIndex(Int32, Int32, Predicate<T>) 述語デリゲートを使用して、コレクションの後半で最初のコンピューター ブックのインデックスを FindComputer 検索します。
FindLastIndex(Int32, Int32, Predicate<T>) 述語デリゲートを使用して、コレクションの後半にある最後のコンピューター ブックのインデックスを FindComputer 検索します。
C#
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; }
    }
}

注釈

Predicate<T>は、渡されたオブジェクトがデリゲートで定義されている条件と一致する場合に を返すtrueメソッドへのデリゲートです。 現在 List<T> の 要素は、デリゲートに個別に渡され Predicate<T> 、 で最初の要素から始まり、最後の要素で終わるので List<T>進みます。 一致が見つかると、処理が停止します。

重要

値型を含むリストを検索するときは、型の既定値が検索述語を満たしていないことを確認します。 それ以外の場合は、一致するものが見つからなかったことを示す既定値と、型の既定値を持つリスト要素を区別する方法はありません。 既定値が検索述語を満たす場合は、代わりに メソッドを FindIndex 使用します。

このメソッドは線形検索を実行します。したがって、このメソッドは O(n) 操作であり、 nCountです。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください