Enumerable 的擴充方法 - Where

 

一、.Where

回傳符合篩選條件後的集合,

Where是Enumerable擴充方法,所以要使用Where擴充方法則事先要include System.Linq命名空間。

 

範例一、

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" };

            IEnumerable query = fruits.Where(fruit => fruit.Length < 6);

            foreach (string fruit in query)
            {
                Console.WriteLine(fruit);
            }
            //輸出為apple、mango、grape

            Console.ReadKey();
        }
    }
}

 

範例二、

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

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"));

            IEnumerable<Person> personIEnumerable = new List<Person>();
            personIEnumerable = personCollection.Where(a => a.id == 2);

            foreach (var item in personIEnumerable)
            {
                Console.WriteLine("id=" + item.id + " , name=" + item.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>.Where 方法