C# lambda表达式

一 CSharp 语音新特性

① C#2.0 引入泛型;
② C#3.0 引入Lamda及Linq;
③ C# 4.0 更多的动态特性dynmaic;

二 泛型(Generic)

List<Book>books=new List<Book>();
Book book=books[0];

//以前要用强制类型转换
ArrayList books=new ArrayList();
Book book=(Book)books[0];

三 匿名方法

① delegate(参数){方法体}
② 可以当一个匿名方法

new Thread(new ThreadStart(delegate(){....}));

③ 可以被隐式转换为一个兼容的委托类型

new Thread(delegate(){.....});

四 Lamda表达式

1 相当于匿名方法的简写

① 省略delegate,深圳省略参数类型;
② 直接用(参数)=>{语句或表达式}
例如

button1.Click+=(sender,e)=>{....}
new Thread(()=>{....}).Start();
PlotFun(x=>x*x,0,100);

五 Linq

LINQ:Language Integrated Query
常见的形式:
① from c in customers;
② where c.Age>10;
③ orderby c.Name;
④ select new{c.Name,c.Phone}
相当于:
① customers;
② .Where(c=>c.Age>10);
③ .OrderBy(c=>c.Name).
④ .Select(c=>new{c.Name,c.Phone})

Linq示例

int[] arr=new int[]{8,9,89,3,56,4,1,58};
var m=from n in arr where n<5 orderby n select n*n;

foreach (var n in m)
{
    Console.WriteLine(n);
}

总结
① 匿名函数使用delegate;
② Lambda表达式使用=>
③ Linq使用from,where,select;

示例
在不同版本C#中使用delegate;
注意:新版本兼容旧版本;
参见:MethodDelegateLamda;

一个label 控件 三个button控件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lambda及相关使用方法
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// 
        /// 示例1 使用线程
        /// 
        /// 
        /// 
        private void button1_Click(object sender, EventArgs e)
        {
            //C# 1.0 使用委托,使用已定义好的函数
            new Thread(new ThreadStart(MyFun)).Start();

            //C#2.0 省略委托 MyFun自动实例化为ThreadStart委托
            new Thread(MyFun).Start();

            //匿名方法
            new Thread(new ThreadStart(delegate () { Console.Write("my function"); })).Start();
            //匿名方法,省略参数列表
            new Thread(new ThreadStart(delegate { Console.Write("my function"); })).Start();

            //匿名方法,自动转委托
            new Thread(delegate () { Console.Write("my function"); }).Start();

            //C# 3.0 Lambad表达式
            new Thread(() => { Console.Write("my function"); }).Start();
        }

        void MyFun()
        {
            Console.Write("my function");
        }
        /// 
        /// 示例2 使用事件
        /// 
        /// 
        /// 
        private void button2_Click(object sender, EventArgs e)
        {
            Example3();
        }

        void Example3()
        {
            //C# 1.0 使用委托,使用自定义函数
            this.MouseMove += new MouseEventHandler(Form1_MouseMove);

            //C# 2.0 自动转委托
            this.MouseMove += Form1_MouseMove;

            Label lbl = this.label1;//这个变量下面使用了闭包(简单地说,使用外部的局部变量)
            this.MouseMove += new MouseEventHandler(delegate (object sender, MouseEventArgs e)
            { lbl.Text = e.X + "," + e.Y; });
            this.MouseMove += delegate (object sender, MouseEventArgs e)
            {
                lbl.Text = e.X + "," + e.Y;
            };

            //C# 3.0 使用Lambda表达式
            this.MouseMove += (object sender, MouseEventArgs e) => { lbl.Text = e.X + "," + e.Y; };
            this.MouseMove += (sender, e) => { lbl.Text = e.X + "," + e.Y; };//可以省略类型
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            this.label1.Text = e.X + "," + e.Y;
        }

        //示例3 数组排序
        class Book
        {
            public string title;
            public double price;
            public Book(string title,double price)
            {
                this.title = title;
                this.price = price;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Random rnd = new Random();
            Book[] books = new Book[10];
            for(int i=0;i<books.Length;i++)
            {
                books[i] = new Book("Book" + i, rnd.Next(100));
            }

            //C#1.0
            Array.Sort(books, new MyComparer());//用一个IComparer

            //C#2.0
            Array.Sort<Book>(books, new Comparison<Book>(delegate (Book book1, Book book2)
            { return (int)(book1.price - book2.price); }));
            Array.Sort<Book>(books,delegate(Book book1,Book book2){
                return (int)(book1.price - book2.price);
            });

            //C# 3.0
            Array.Sort<Book>(books, (Book book1, Book book2) => (int)(book1.price - book2.price));
            Array.Sort<Book>(books, (book1, book2) => (int)(book1.price - book2.price));//省略参数类型

            //使用Linq
            IOrderedEnumerable<Book> result= from book in books orderby book.price select book;

            var result2 = from book in books where book.price >= 0 orderby book.price select book.title;

            foreach (string s in result2) Console.Write(s);

            var result3 = books
                .Where<Book>(b => b.price >= 0)
                .OrderBy<Book, double>(b => b.price, Comparer<double>.Default)
                .Select<Book, Book>(book => book);
            foreach (Book b in result3)
                Console.Write(b.price + " ");
        }

        class MyComparer:System.Collections.IComparer
        {
            public int Compare(object x1,object x2)
            {
                return (int)(((Book)x1).price - ((Book)x2).price);
            }
        }
    }
}

你可能感兴趣的:(C#程序设计,c#,linq,开发语言)