List<string> people = new List<string> { "name1", "name2", "joe", "another name", "etc" };
string person = people.Find(person => person.Contains("Joe"));
与
public string FindPerson(string nameContains, List<string> persons)
{
foreach (string person in persons)
if (person.Contains(nameContains))
return person;
return null;
}
微软为我们提供了一种更简洁、更方便的方式来创建匿名委托,即Lambda表达式。然而,这个语句的表达式部分并没有引起太多注意。微软发布了一个完整的命名空间System.Linq.Expressions,它包含了基于lambda表达式创建表达式树的类。表达式树由表示逻辑的对象组成。例如,x = y + z是一个表达式,它可能是. net中的表达式树的一部分。考虑以下(简单的)例子:
using System;
using System.Linq;
using System.Linq.Expressions;
namespace ExpressionTreeThingy
{
class Program
{
static void Main(string[] args)
{
Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
Console.WriteLine(del(5)); //we are just invoking a delegate at this point
Console.ReadKey();
}
}
}