LinQExtension Method

现在假设有以下字符串数组:

string[] names = { "bruce", "aron", "matt", "nancy", "grant", "jet", "matthew" };

我想取出所有名字长度大于等于4的,我们可以这样用linq查询语句:

var nameList = from name in names where name.Length >= 4 select name;

其实这句语句可以写成这样:

var nameList = names.Where(name => name.Length >= 4).Select(name => name);

这好像names有两个方法:Where,Select,其实这两个方法是linq的扩展方法

namespace System.Linq
{
    // 摘要:
    //     提供一组用于查询实现 System.Collections.Generic.IEnumerable<T> 的对象的 static(在 Visual
    //     Basic 中为 Shared)方法。
    public static class Enumerable
    {
        ……
        //
        // 摘要:
        //     将序列中的每个元素投影到新表中。
        //
        // 参数:
        //   source:
        //     一个值序列,要对该序列调用转换函数。
        //
        //   selector:
        //     应用于每个元素的转换函数。
        //
        // 类型参数:
        //   TSource:
        //     source 中的元素的类型。
        //
        //   TResult:
        //     selector 返回的值的类型。
        //
        // 返回结果:
        //     一个 System.Collections.Generic.IEnumerable<T>,其元素为对 source 的每个元素调用转换函数的结果。
        //
        // 异常:
        //   System.ArgumentNullException:
        //     source 或 selector 为 null。
        public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);

  ……

        //
        // 摘要:
        //     基于谓词筛选值序列。
        //
        // 参数:
        //   source:
        //     要筛选的 System.Collections.Generic.IEnumerable<T>。
        //
        //   predicate:
        //     用于测试每个元素是否满足条件的函数。
        //
        // 类型参数:
        //   TSource:
        //     source 中的元素的类型。
        //
        // 返回结果:
        //     一个 System.Collections.Generic.IEnumerable<T>,包含输入序列中满足条件的元素。
        //
        // 异常:
        //   System.ArgumentNullException:
        //     source 或 predicate 为 null。
        public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
  ……
      }
}
 
我们完全可以写成:

 var nameWhere = System.Linq.Enumerable.Where(names, name => name.Length >= 4);
 var nameList =System.Linq.Enumerable.Select(nameWhere, name => name);
 可以看到返回值是一个IEnumerable<TSource>类型,我们可以不用CLR infer 将var改为IEnumerable<string>
 IEnumerable<string> nameWhere = System.Linq.Enumerable.Where(names, name => name.Length >= 4);
 IEnumerable<string> nameList = System.Linq.Enumerable.Select(nameWhere, name => name);

扩展方法的关键就是这个this

我可以为我的names数组写一个扩展方法,假设获得数组的大小

public static class TestExtensionClass

    {

        public static int GetLength(this string[] s)

        {

            return s.Length;

        }

    }

var namesLength = names.GetLength();

因为是this所以就是自身,而GetLength()又是静态函数。

原文地址:https://www.cnblogs.com/matthew/p/1319653.html