C#高级编程四十三天
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lambda表达式
{
class Program
{
public delegate int del(int i);
static void Main(string[] args)
{
List<string> fruits = new List<string> { "apple", "orange", "blueberry", "passionfruit" };
IEnumerable<string> query = fruits.Where(fruit => fruit.Length <6);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
Console.ReadKey();
}
}
}
输出结果是:apple
一般where都是跟Lambda表达式一起使用的,where语法包含在Linq命名空间下,何为Lambda表达式呢,简单地说就是匿名函数,也跟委托匿名差不多
案例:
class Program
{
//声明委托类型
public delegate int del(int i);
static void Main(string[] args)
{
//定义一个委托事件
del MyDelegate = x => x * 6;
int j = MyDelegate(5);
Console.WriteLine(j);
Console.ReadKey();
}
}
输出:30
估计很容易看明白.
Lambda表达式规则:
表达式位于=>运算符的右侧(input parameters)=>expression
当Lambda只有一个输入参数的时候,括号才是可选的,否则括号是必须的.
例如:(x,y)=>x==y
有时当编译器无法判断类型的时候,出现这种情况,你可以显示指定参数类型.
例如:(int x,string y)=>s.length>x
当使用空括号表示指定0个参数
例如:()=SomeMethod();
案例:
class Program
{
//声明委托类型
public delegate void ShowStr(string s);
static void Main(string[] args)
{
//定义一个委托事件
ShowStr myshow = n => { string s = n + " " + "world"; Console.WriteLine(s); };
myshow("hello");
Console.ReadKey();
}
}
输出: hello world
分析:Lambda符号左侧是参数
其实理解了委托和实践就很容易理解Lambda,说白了就是匿名委托,再进一步直白一点就是匿名函数.
稍微复杂一点的Lambda表达式
static void Main(string[] args)
{
//表达式的声明
Func<int, bool> myFunc = x => x == 5;
bool res = myFunc(4);//这里传递5就是true
Console.WriteLine(res);
Console.ReadKey();
}
分析:上面声明的表达式,是以int类型作为参数,然后做一个比较,返回的是一个bool值.
如果参数是Expression<Func>时,你也可以提供Lambda表达式,例如在System.Linq.Queryable内定义的标准查询运算符中.如果指定Expression<Func>参数,lambda将编译为表达式的目录树.
下例显示了一个标准查询运算符
static void Main(string[] args)
{
//表达式的声明
int[] array = {1,2,3,4,5,6,7,8,9 };
int oddNumbers = array.Count(n => n % 2 == 1);
Console.WriteLine(oddNumbers);
Console.ReadKey();
}
分析:该例的作用是用来计算数组中奇数的个数
案例:
class Program
{
static void Main(string[] args)
{
//表达式的声明
int[] array = {1,2,3,4,5,6,7,8,9 };
//计算出小于6左侧的数字
var firstNumberLessThan6 = array.TakeWhile(n => n < 6);
Console.WriteLine("一直输出,遇到大于6的数就停止");
foreach (var item in firstNumberLessThan6)
{
Console.WriteLine(item + " "); ;
}
var firstSmallNumbers = array.TakeWhile((n, index) => n >= index);
Console.WriteLine("输出索引小于值的数");
foreach (var item in firstSmallNumbers)
{
Console.WriteLine(item+" ");
}
Console.ReadKey();
}
}
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69522.html