Lambda表达式

一、什么时候使用Lambda表达式

总的来说,Lambda 表达式可以用在任何需要使用匿名方法,或是代理的地方。编译器会将Lambda表达式编译为标准的匿名方法(可以使用ildasm.exe or reflector.exe得到确认)。

比如:

List<int> evenNumbers = list.FindAll(i => (i% 2) == 0);


被编译为

List<int> evenNumbers = list.FindAll(delegate (int i)
{
return (i % 2) == 0;
});


二、Lambda表达式的解读

Lambda表达式的写法

ArgumentsToProcess (参数)=> StatementsToProcessThem(报表)


比如

// "i" is our parameter list.
// "(i % 2) == 0" is our statement set to process "i".
List<int> evenNumbers = list.FindAll(i => (i% 2) == 0);


应该这样来理解

// My list of parameters (in this case a singleinteger named i)
// will be processed by the expression (i % 2) == 0.
List<int> evenNumbers = list.FindAll((i) => ((i% 2) == 0));


可以显式指定输入参数的类型

List<int> evenNumbers = list.FindAll((int i) => (i % 2) == 0);


可以使用括号把输入参数和表达式括起来,如果参数或处理表达式只有一个,可以省略括号

List<int> evenNumbers = list.FindAll((i) => ((i% 2) == 0));


有多行处理表达式时,需要使用花括号包起来

List<int> evenNumbers = list.FindAll((i) =>
{
Console.WriteLine("valueof i is currently: {0}", i);
bool isEven = ((i % 2) == 0);
return isEven;
});


当输入参数有多个时

SimpleMath m = new SimpleMath();
m.SetMathHandler((msg, result) =>
{Console.WriteLine("Message:{0}, Result: {1}", msg, result);});


或者显式指定输入参数类型

m.SetMathHandler((string msg, int result) =>
{Console.WriteLine("Message:{0}, Result: {1}", msg, result);});

 
当没有输入参数时

VerySimpleDelegate d = new VerySimpleDelegate( () => {return "Enjoy your string!";} );


 

Lambda表达式可以在使用代理和匿名代理的地方

1、命名函数

public class Common
{
public delegate bool IntFilter(int i);
public static int[] FilterArrayOfInts(int[] ints, IntFilter filter)
{
ArrayList aList = new ArrayList();
foreach (int i in ints)
{
if (filter(i))
{
aList.Add(i);
}
}
return ((int[])aList.ToArray(typeof(int)));
}
}

 

public class Application
{
public static bool IsOdd(int i)
{
return ((i & 1) == 1);
}
}

 

using System.Collections;
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] oddNums = Common.FilterArrayOfInts(nums,Application.IsOdd);
foreach (int i in oddNums)
Console.WriteLine(i);
2、匿名函数

int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] oddNums =
Common.FilterArrayOfInts(nums, delegate(int i) { return ((i & 1) == 1); });
foreach (int i in oddNums)
Console.WriteLine(i);
3、Lambda表达式

int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int[] oddNums = Common.FilterArrayOfInts(nums,i => ((i & 1) == 1));
foreach (int i in oddNums)
Console.WriteLine(i);
三种方式的比较

int[] oddNums = // using named method
Common.FilterArrayOfInts(nums,Application.IsOdd);
int[] oddNums = // using anonymous method
Common.FilterArrayOfInts(nums,delegate(int i){return((i & 1) == 1);});
int[] oddNums = // using lambda expression
Common.FilterArrayOfInts(nums,i => ((i & 1) == 1));
命名函数虽然简短,但是而外还要定义处理函数,优点是可以重用


 


匿名方法


匿名方法就是没名儿的委托。虽然没名,但是必须加”delegate“来表示我没名。

// Create a delegateinstance
delegate void Del(int x);

// Instantiate the delegate using an anonymous method
Del d = delegate(int k) { /* ... */ };
Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n);};
delegate void Printer(string s);
Printer p = delegate(string j)
{
System.Console.WriteLine(j);
};
p("The delegate using the anonymous method is called.");

delegate string Printer(string s);
private void button1_Click(object sender, EventArgs e)
{
 Printer p =delegate(string j)
{
   return (j)+"烦死了";
};
Console.WriteLine(p("The delegate using the anonymous method is called."));
}

或者有名。。。。的匿名委托。。。。哈哈,我在抽风还是微软在抽风。让我死吧。

delegate void Printer(string s);
private void button1_Click(object sender, EventArgs e)
{
Printer p = new Printer(Form1.DoWork);
p("http://www.dc9.cn/");
}
static void DoWork(string k)
{
System.Console.WriteLine(k);
}

匿名方法就完了。


Lamdba就是 (int x)=>{x+1}就是这样的。。。例子呢就是上面写了的一段用lambda就这样写

delegate string Printer(string s);
private void button1_Click(object sender, EventArgs e)
{
Printer p = j => j+"烦死了!!!";
Console.WriteLine(p("The delegate using the anonymous method is called."));
}

还能这么用
和上面那个一样,就是简化了。

public Form1()
{
InitializeComponent();
 this.Click += (s, e) => { MessageBox.Show(((MouseEventArgs)e).Location.ToString());};
}


超难+===>?其实不难。难的是转换成一般的函数怎么写呢????


Where是Enumerable的一个方法。3.5才有的。里面的参数是Func<(Of <(T, TResult>)>)泛型委托


Func<(Of<(T, TResult>)>) 泛型委托


using System;
delegate string ConvertMethod(string inString);

public class DelegateExample
{
   public static void Main()
   {
  // Instantiate delegate to referenceUppercaseString method
  ConvertMethod convertMeth = UppercaseString;
  string name = "Dakota";
  // Use delegate instance to call UppercaseStringmethod
  Console.WriteLine(convertMeth(name));
   }


   private static string UppercaseString(stringinputString)
   {
  return inputString.ToUpper();
   }
}

写成泛型委托是

using System;
public class GenericFunc
{
   public static void Main()
   {
  // Instantiate delegate to referenceUppercaseString method
  Func<string, string> convertMethod= UppercaseString;
  string name = "Dakota";
  // Use delegate instance to call UppercaseStringmethod
  Console.WriteLine(convertMethod(name));
   }
   private static string UppercaseString(stringinputString)
   {
  return inputString.ToUpper();
   }
}


于是应用到Linq,再变换到lambda

delegate bool TestFunc(string fruit);
private void button1_Click(object sender, EventArgs e)
{
List<string> fruits =new List<string> { "apple", "http://www.dc9.cn","banana", "mango",
"orange", "blueberry", "grape", "strawberry"};
TestFunc f = new TestFunc(DoWork);
Func<string, bool> f2 = DoWork;
IEnumerable<string> query = fruits.Where(f2);
foreach (string fruit in query)
Console.WriteLine(fruit);
   }

private static bool DoWork(string k)
{
  return   k.Length < 6;
   }

能用。

==========================================================

 

delegate bool TestFunc(string fruit);
private void button1_Click(object sender, EventArgs e)
{
List<string> fruits =new List<string> { "apple", "passionfruit","banana", "mango",
"orange", "blueberry", "grape", "http://www.dc9.cn"};
TestFunc f = DoWork;
Func<string, bool> f2 =k=> k.Length < 6;
IEnumerable<string> query = fruits.Where(f2);
foreach (string fruit in query)
Console.WriteLine(fruit);
   }

private static bool DoWork(string k)
{
  return   k.Length < 6;
   }

也能用

 

========================================================

漫画

private void button1_Click(object sender, EventArgse)
{
List<string> fruits =new List<string> { "apple", "passionfruit","banana", "mango",
"orange", "blueberry", "grape", "http://www.dc9.cn"};
IEnumerable<string> query = fruits.Where(
delegate(string k){
return k.Length < 6;
}
);
foreach (string fruit in query)
Console.WriteLine(fruit);
   }

能用~

private void button1_Click(object sender, EventArgse)
{
List<string> fruits =new List<string> { "apple", "passionfruit","banana", "mango",
"orange", "blueberry", "grape", "http://www.dc9.cn"};
IEnumerable<string> query = fruits.Where(k=>k.Length<6);
foreach (string fruit in query)
Console.WriteLine(fruit);
   }

最后,lambda,能用~~~~就酱紫了~~~~

  publicdelegate int mydg(int a, int b);
  public static class LambdaTest
  {
  public static int oper(this int a,int b, mydg dg)
  {
  return dg(a, b);
  }
  }
Console.WriteLine(1.oper(2, (a, b) => a + b));
Console.WriteLine(2.oper(1, (a, b) => a - b));

 

基于html+python+Apriori 算法、SVD(奇异值分解)的电影推荐算法+源码+项目文档+算法解析+数据集,适合毕业设计、课程设计、项目开发。项目源码已经过严格测试,可以放心参考并在此基础上延申使用,详情见md文档 电影推荐算法:Apriori 算法、SVD(奇异值分解)推荐算法 电影、用户可视化 电影、用户管理 数据统计 SVD 推荐 根据电影打分进行推荐 使用 svd 模型计算用户对未评分的电影打分,返回前 n 个打分最高的电影作为推荐结果 n = 30 for now 使用相似电影进行推荐 根据用户最喜欢的前 K 部电影,分别计算这 K 部电影的相似电影 n 部,返回 K*n 部电影进行推荐 K = 10 and n = 5 for now 根据相似用户进行推荐 获取相似用户 K 个,分别取这 K 个用户的最喜爱电影 n 部,返回 K*n 部电影进行推荐 K = 10 and n = 5 for now Redis 使用 Redis 做页面访问次数统计 缓存相似电影 在使用相似电影推荐的方式时,每次请求大概需要 6.6s(需要遍历计算与所有电影的相似度)。 将相似电影存储至 redis 中(仅存储 movie_id,拿到 movie_id 后还是从 mysql 中获取电影详细信息), 时间缩短至:93ms。 十部电影,每部存 top 5 similar movie 登录了 1-6 user并使用了推荐系统,redis 中新增了 50 部电影的 similar movie,也就是说,系统只为 6 为用户计算了共 60 部电影的相似度,其中就有10 部重复电影。 热点电影重复度还是比较高的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值