List Find 方法

 

一、.Find

回傳符合條件的單一元素

範例一、

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List fruits =
                new List { "apple", "passionfruit", "banana", "mango", 
                    "orange", "blueberry", "grape", "strawberry" };

            string query2 = fruits.Find(fruit => fruit.Length < 6);
            Console.WriteLine(query2);
            //輸出為apple

            Console.ReadKey();
        }
    }
}

 

範例二、

using System;
using System.Collections.Generic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> personCollection = new List<Person>();
            personCollection.Add(new Person(1, "Tim"));
            personCollection.Add(new Person(2, "Brooke"));
            personCollection.Add(new Person(3, "John"));

            Person Person = personCollection.Find(a => a.id == 2);

            Console.WriteLine("id=" + Person.id + " , name=" + Person.name);
            Console.ReadKey();
        }
    }

    class Person
    {
        public int id { get; set; }
        public string name { get; set; }
        public Person(int id, string name)
        {
            this.id = id;
            this.name = name;
        }
    }
}

 

参考資料:

List<T>.Find Method