關於lambda運算式的一些學習——基於謂詞篩選值序列

來源:互聯網
上載者:User

標籤:style   blog   color   使用   strong   os   

今天看了一些關於lambda運算式的知識,然後對於Func<T,TResult>泛型委派不太熟悉,便查了查相關資料,又引出來了基於謂詞篩選值序列這個對我來說的新鮮知識點,於是去查MSDN,以下是看到的一些相關介紹:

此方法通過使用順延強制實現。 即時傳回值為一個對象,該Object Storage Service執行操作所需的所有資訊。 只有通過直接調用對象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)來枚舉該對象時,才執行此方法表示的查詢。

在查詢運算式文法中,where (Visual C#) 或 Where (Visual Basic) 子句轉換為 Where<TSource>(IEnumerable<TSource>, Func<TSource, Boolean>) 的一個調用。

List<string> fruits =                new List<string> { "apple", "passionfruit", "banana", "mango",                                 "orange", "blueberry", "grape", "strawberry" };            IEnumerable<string> query = fruits.Where(fruit => fruit.Length < 6);            foreach (string fruit in query)            {                Console.WriteLine(fruit);            }

上面這段代碼的輸出結果:

applemangogrape


上面是一個簡單地樣本,接下來看一個稍微複雜的,直接上代碼了:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace LambdaTest{    class Program    {        static void Main(string[] args)        {            List<int> list = new List<int>();            list.AddRange(new int[] { 7, 6, 10, 1, 2, 3, 4, 5, 8 });            Func<int, bool> fi = new Func<int, bool>(MoreThan5);            IEnumerator<int> ie = list.Where<int>(fi).GetEnumerator();            //效果與list.Where<int>(fi).GetEnumerator()一致            //IEnumerator<int> ie = list.Where<int>(x => x > 5).GetEnumerator();            //效果與list.Where<int>(fi).GetEnumerator()一致            //IEnumerator<int> ie = list.Where(delegate(int i){return i > 5;}).GetEnumerator();            while (ie.MoveNext())            {                Console.WriteLine(ie.Current.ToString());            }            Console.ReadKey();        }        public static bool MoreThan5(int i)        {            return i > 5;        }    }}

上面這段代碼的輸出結果:

7

6

10

8

 

其中用到了IEnumerator和泛型以及委託的相關知識,希望可以作為引子,給大家帶來一點新的趕腳~~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.