如何:为 LINQ 查询添加自定义方法

可以通过向 IEnumerable<T> 接口添加扩展方法来扩展可用于 LINQ 查询的方法集。 例如,除标准平均值运算或最大值运算之外,您可以创建自定义聚合方法来从值序列计算单个值。 还可以创建一个用作自定义筛选器的方法,或创建针对值序列的特定数据转换并返回新的序列。 DistinctSkip<TSource>Reverse<TSource> 就属于此类方法示例。

当扩展 IEnumerable<T> 接口时,可以将您的自定义方法用于任意可枚举集合。 有关更多信息,请参见扩展方法(C# 编程指南)扩展方法 (Visual Basic)

添加聚合方法

聚合方法可从一组值计算单个值。 LINQ 提供多种聚合方法,其中包括 AverageMinMax。 您可以通过将扩展方法添加到 IEnumerable<T> 接口创建自己的聚合方法。

以下代码示例演示如何创建称为 Median 的扩展方法以计算类型为 double 的数值序列的中值。

Imports System.Runtime.CompilerServices

Module LINQExtension

    ' Extension method for the IEnumerable(of T) interface. 
    ' The method accepts only values of the Double type.
    <Extension()> 
    Function Median(ByVal source As IEnumerable(Of Double)) As Double
        If source.Count = 0 Then
            Throw New InvalidOperationException("Cannot compute median for an empty set.")
        End If

        Dim sortedSource = From number In source 
                           Order By number

        Dim itemIndex = sortedSource.Count \ 2

        If sortedSource.Count Mod 2 = 0 Then
            ' Even number of items in list.
            Return (sortedSource(itemIndex) + sortedSource(itemIndex - 1)) / 2
        Else
            ' Odd number of items in list.
            Return sortedSource(itemIndex)
        End If
    End Function
End Module
public static class LINQExtension
{
    public static double Median(this IEnumerable<double> source)
    {
        if (source.Count() == 0)
        {
            throw new InvalidOperationException("Cannot compute median for an empty set.");
        }

        var sortedList = from number in source
                         orderby number
                         select number;

        int itemIndex = (int)sortedList.Count() / 2;

        if (sortedList.Count() % 2 == 0)
        {
            // Even number of items.
            return (sortedList.ElementAt(itemIndex) + sortedList.ElementAt(itemIndex - 1)) / 2;
        }
        else
        {
            // Odd number of items.
            return sortedList.ElementAt(itemIndex);
        }
    }
}

可以使用与从 IEnumerable<T> 接口调用其他聚合方法的相同方式为任意可枚举集合调用此扩展方法。

提示

在 Visual Basic 中,您可以使用方法调用,也可以使用 Aggregate 或 Group By 子句的标准查询语法。 有关更多信息,请参见Aggregate 子句 (Visual Basic)Group By 子句 (Visual Basic)

以下代码示例演示如何针对类型为 double 的数组使用 Median 方法。

        Dim numbers1() As Double = {1.9, 2, 8, 4, 5.7, 6, 7.2, 0}

        Dim query1 = Aggregate num In numbers1 Into Median()

        Console.WriteLine("Double: Median = " & query1)



...


        ' This code produces the following output:
        '
        ' Double: Median = 4.85

        double[] numbers1 = { 1.9, 2, 8, 4, 5.7, 6, 7.2, 0 };

        var query1 = numbers1.Median();

        Console.WriteLine("double: Median = " + query1);



...


/*
 This code produces the following output:

 Double: Median = 4.85
*/

重载聚合方法以接受各种类型

可以重载聚合方法以便其能够接受各种各样的类型。 标准方法是为每种类型均创建一个重载。 还有一种方法是创建一种采用泛型类型的重载,然后使用委托将其转换为指定的类型。 还可以结合使用这两种方法。

为每种类型创建重载

可以为想要支持的每种类型创建一个特定的重载。 以下代码示例演示适用于 integer 类型的 Median 方法的重载。

' Integer overload

<Extension()> 
Function Median(ByVal source As IEnumerable(Of Integer)) As Double
    Return Aggregate num In source Select CDbl(num) Into med = Median()
End Function
//int overload

public static double Median(this IEnumerable<int> source)
{
    return (from num in source select (double)num).Median();
}

现在,您可以为 integer 和 double 两种类型调用 Median 重载,如以下代码所示:

        Dim numbers1() As Double = {1.9, 2, 8, 4, 5.7, 6, 7.2, 0}

        Dim query1 = Aggregate num In numbers1 Into Median()

        Console.WriteLine("Double: Median = " & query1)



...


        Dim numbers2() As Integer = {1, 2, 3, 4, 5}

        Dim query2 = Aggregate num In numbers2 Into Median()

        Console.WriteLine("Integer: Median = " & query2)



...


' This code produces the following output:
'
' Double: Median = 4.85
' Integer: Median = 3
        double[] numbers1 = { 1.9, 2, 8, 4, 5.7, 6, 7.2, 0 };

        var query1 = numbers1.Median();

        Console.WriteLine("double: Median = " + query1);



...


        int[] numbers2 = { 1, 2, 3, 4, 5 };

        var query2 = numbers2.Median();

        Console.WriteLine("int: Median = " + query2);



...


/*
 This code produces the following output:

 Double: Median = 4.85
 Integer: Median = 3
*/

创建泛型重载

还可以创建接受泛型对象序列的重载。 此重载将委托作为参数,并使用其将泛型类型的对象序列转换为指定的类型。

以下代码演示 Median 方法的重载,该重载采用 Func<T, TResult> 委托作为参数。 此委托采用泛型类型 T 的对象,并返回类型为 double 的对象。

' Generic overload.

<Extension()> 
Function Median(Of T)(ByVal source As IEnumerable(Of T), 
                      ByVal selector As Func(Of T, Double)) As Double
    Return Aggregate num In source Select selector(num) Into med = Median()
End Function
// Generic overload.

public static double Median<T>(this IEnumerable<T> numbers,
                       Func<T, double> selector)
{
    return (from num in numbers select selector(num)).Median();
}

现在可以为任何类型的对象序列调用 Median 方法。 如果该类型没有自己的方法重载,则需要传递委托参数。 在 Visual Basic 和 C# 中,可以为此使用 lambda 表达式。 此外,仅在 Visual Basic 中时,如果使用 Aggregate 或 Group By 子句,而不使用方法调用,则可以传递此子句范围内的任何值或表达式。

以下代码示例演示如何为整数或字符串数组调用 Median 方法。 对字符串而言,将计算数组中字符串长度的中值。 该示例演示如何在各种情况下将 Func<T, TResult> 委托参数传递给 Median 方法。

Dim numbers3() As Integer = {1, 2, 3, 4, 5}

' You can use num as a parameter for the Median method 
' so that the compiler will implicitly convert its value to double.
' If there is no implicit conversion, the compiler will
' display an error message.

Dim query3 = Aggregate num In numbers3 Into Median(num)

Console.WriteLine("Integer: Median = " & query3)

Dim numbers4() As String = {"one", "two", "three", "four", "five"}

' With the generic overload, you can also use numeric properties of objects.

Dim query4 = Aggregate str In numbers4 Into Median(str.Length)

Console.WriteLine("String: Median = " & query4)

' This code produces the following output:
'
' Integer: Median = 3
' String: Median = 4
int[] numbers3 = { 1, 2, 3, 4, 5 };

/* 
  You can use the num=>num lambda expression as a parameter for the Median method 
  so that the compiler will implicitly convert its value to double.
  If there is no implicit conversion, the compiler will display an error message.          
*/

var query3 = numbers3.Median(num => num);

Console.WriteLine("int: Median = " + query3);

string[] numbers4 = { "one", "two", "three", "four", "five" };

// With the generic overload, you can also use numeric properties of objects.

var query4 = numbers4.Median(str => str.Length);

Console.WriteLine("String: Median = " + query4);

/*
 This code produces the following output:

 Integer: Median = 3
 String: Median = 4
*/

添加返回集合的方法

可以使用返回值序列的自定义查询方法扩展 IEnumerable<T> 接口。 在这种情况下,该方法必须返回类型为 IEnumerable<T> 的集合。 此类方法可用于将筛选器或数据转换应用于值序列。

以下示例演示如何创建名为 AlternateElements 的扩展方法,该方法从集合中的首个元素起,每隔一个元素返回一个元素值。

' Extension method for the IEnumerable(of T) interface. 
' The method returns every other element of a sequence.

<Extension()> 
Function AlternateElements(Of T)(
    ByVal source As IEnumerable(Of T)
    ) As IEnumerable(Of T)

    Dim list As New List(Of T)
    Dim i = 0
    For Each element In source
        If (i Mod 2 = 0) Then
            list.Add(element)
        End If
        i = i + 1
    Next
    Return list
End Function
// Extension method for the IEnumerable<T> interface. 
// The method returns every other element of a sequence.

public static IEnumerable<T> AlternateElements<T>(this IEnumerable<T> source)
{
    List<T> list = new List<T>();

    int i = 0;

    foreach (var element in source)
    {
        if (i % 2 == 0)
        {
            list.Add(element);
        }

        i++;
    }

    return list;
}

如同从 IEnumerable<T> 接口调用其他方法一样,您可以为任何可枚举集合调用此扩展方法,如以下代码所示:

Dim strings() As String = {"a", "b", "c", "d", "e"}

Dim query = strings.AlternateElements()

For Each element In query
    Console.WriteLine(element)
Next

' This code produces the following output:
'
' a
' c
' e
string[] strings = { "a", "b", "c", "d", "e" };

var query = strings.AlternateElements();

foreach (var element in query)
{
    Console.WriteLine(element);
}
/*
 This code produces the following output:

 a
 c
 e
*/

请参见

参考

IEnumerable<T>

扩展方法(C# 编程指南)

概念

扩展方法 (Visual Basic)