C# Predicate委託

來源:互聯網
上載者:User

Predicate在集合搜尋和WPF資料繫結中用途廣泛,其調用形式:  

    調用形式:Predicate<object>(Method)/Predicate<參數類型>(方法)
         1.<>表示泛型,可以接受任何類型的參數

                           2.(Method)可以接受方法為參數進行傳遞,表示一個委託

                   3.傳回型別為bool型,表示成功與否

一個例子,在empList中尋找特定項:

class Employee{    private string _firstName;    private string _lastName;    //private int _empCode;    private string _designation;    public Employee()    { }    public Employee(string firstName, string lastName, string designation)    {        _firstName = firstName;        _lastName = lastName;        _designation = designation;    }    /// <summary>    /// Property First Name    /// </summary>    public string FirstName     {        get { return _firstName; }        set { _firstName = value; }    }    /// <summary>    /// Property Last Name    /// </summary>    public string LastName    {        get { return _lastName; }        set { _lastName = value; }    }            public string Designation    {        get { return _designation; }        set { _designation = value; }    }
1.傳統方法

定義一個搜尋方法:

  static bool EmpSearch(Employee emp)                {                    if (emp.FirstName == "Anshu")                            return true;                    else                            return false;                }

使用泛型的Find()方法,Find()內部自動迭代調用EmpSearch方法

Predicate<Employee> pred = new Predicate<Employee(EmpSearch);Employee emp = empList.Find(pred);
2.使用匿名方法
emp = empList.Find(delegate(Employee e){         if(e.FirstName == "Anshu")               return true;         else                return false;                });   

不需要重新顯式的定義方法,代碼更加簡潔

3.使用lambda運算式
emp = new Employee();            emp = empList.Find((e)=> {return (e.FirstName == "Anshu");});

(e)=>表示傳遞一個參數,參數類型能夠自動解析

4.搜尋列表
List<Employee> employees = new List<Employee>();employees = empList.FindAll((e) => { return (e.FirstName.Contains("J")); });
5.搜尋索引

通過指定開始索引和搜尋條目的數量來縮小搜尋的範圍

int index = empList.FindIndex(0,2,(e) => { return (e.FirstName.Contains("J")); 

表示從索引0開始,搜尋2個條目。

6.List中常用的比較子委託

給下列數組排序

var data = new List<int>();var rand = new Random();Console.WriteLine("Unsorted list");for (int i = 0; i < 10; i++){        int d =rand.Next(0,100);        data.Add(d);        Console.Write("{0} ",d);}

使用Lampda表示式進行從大到小排序

  data.Sort((e1, e2) => {return e1.CompareTo(e2) ;});

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.