查询操作符与扩展方法解析(1)
查询操作符是LINQ中的另外一项重要设施,LINQ使
用扩展方法来定义查询操作符,例如where操作符:
namespace System.Linq {
public static class Enumerable {
public static IEnumerable<T> Where<T>(
this IEnumerable<T> source, Func<T, bool> predicate) {
foreach (T item in source)
if (predicate(item))
yield return item;
}
}
}
查询操作符与扩展方法解析(2)
普通的方式来调用扩展方法:
IEnumerable<string> query = Enumerable.Where(names,
s => s.Length < 6);
C#语言允许我们使用如下的方式来调用扩展方法:
IEnumerable<string> query = names.Where(s => s.Length < 6);