
说明(2017-11-22 18:15:48):
1. Lambda表达式里面用了匿名委托,感觉理解起来还是挺难的。求偶数的例子模拟了Linq查询里的一个where方法。
2. 蒋坤说求水仙花数那个例子,“能看就看,看不懂就算了!”T_T
Linq方法求偶数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace _00_Test
{
class Program
{
static void Main(string[] args)
{
//Linq方法求偶数
int[] nums = { , , , , , , , , , };
List<int> list = new List<int>();
//where关键字
foreach (int n in nums.Where(e => e % == ))
{
Console.WriteLine(n);
}
Console.ReadKey();
}
}
}
模拟Linq方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace _00_Test
{
public delegate bool MyDel(int n);
class Program
{
static void Main(string[] args)
{
int[] nums = { , , , , , , , , , };
int[] ns = MyWhere(nums, e => e % == );
Console.ReadKey();
}
public static int[] MyWhere(int[] nums, MyDel myDel)
{
List<int> list = new List<int>();
foreach (int n in nums)
{
//执行if时,会跳到"e % 2 == 0"语句,myDel(n)就相当于e => e % 2 == 0。
if (myDel(n))
{
list.Add(n);
}
}
return list.ToArray();
}
}
}
正常求水仙花数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace _06_Lambda水仙花数
{
class Program
{
public delegate List<int> MyDel(List<int> n);
static void Main(string[] args)
{
List<int> nums = new List<int>();
for (int i = ; i < ; i++)
{
nums.Add(i);
}
int[] nums2 = GetFlowers(nums.ToArray());
}
public static int[] GetFlowers(int[] nums)
{
List<int> list = new List<int>();
for (int i = ; i < nums.Length; i++)
{
//如123
int num = nums[i];
int n1 = num % ;
int n2 = num / % ;
int n3 = num / ;
int num2 = Convert.ToInt32(Math.Pow(Convert.ToDouble(n1), Convert.ToDouble()) + Math.Pow(Convert.ToDouble(n2), Convert.ToDouble()) + Math.Pow(Convert.ToDouble(n3), Convert.ToDouble()));
if (num == num2)
{
list.Add(num);
}
}
return list.ToArray();
}
}
}
Lambda表达式求水仙花,把上面的求偶数改了一下e=>{}大括号里面的内容就可以了,这么看似乎是简单复用了一些:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace _00_Test
{
public delegate bool MyDel(int n);
class Program
{
static void Main(string[] args)
{
//生成100到1000的整数
List<int> nums = new List<int>();
for (int i = ; i < ; i++)
{
nums.Add(i);
}
//e=>{},大括号中,判断参数e是否符合水仙花条件,返回bool值。
int[] ns = MyWhere(nums.ToArray(), e =>
{
int n1 = e % ;
int n2 = e / % ;
int n3 = e / ;
int num2 = Convert.ToInt32(Math.Pow(Convert.ToDouble(n1), Convert.ToDouble()) + Math.Pow(Convert.ToDouble(n2), Convert.ToDouble()) + Math.Pow(Convert.ToDouble(n3), Convert.ToDouble()));
return num2 == e;
});
Console.ReadKey();
}
public static int[] MyWhere(int[] nums, MyDel myDel)
{
List<int> list = new List<int>();
foreach (int n in nums)
{
//执行if时,会跳到"e % 2 == 0"语句,myDel(n)就相当于e => {}。
if (myDel(n))
{
list.Add(n);
}
}
return list.ToArray();
}
}
}