大网数据广告活动
.NET 与 C# 开发

如何:为 LINQ 查询 (Visual Basic 中) 添加自定义方法

· 52CE 我爱测

可通过向 接口添加扩展方法扩展可用于 LINQ 查询的方法集。 例如,除了标准平均值或最大值运算,还可以创建自定义聚合方法,从一系列值计算单个值。 此外可以创建一个方法,用作一个值序列的自定义筛选器或用于对其进行特定数据转换,并返回新的序列。 、 和 就是此类方法的示例。

可通过向 xref:System.Collections.Generic.IEnumerable`1 接口添加扩展方法扩展可用于 LINQ 查询的方法集。 例如,除了标准平均值或最大值运算,还可以创建自定义聚合方法,从一系列值计算单个值。 此外可以创建一个方法,用作一个值序列的自定义筛选器或用于对其进行特定数据转换,并返回新的序列。 xref:System.Linq.Enumerable.Distinct*、xref:System.Linq.Enumerable.Skip* 和 xref:System.Linq.Enumerable.Reverse* 就是此类方法的示例。

扩展 xref:System.Collections.Generic.IEnumerable`1 接口时,可以将自定义方法应用于任何可枚举集合。 有关详细信息,请参阅扩展方法。

添加聚合对象

聚合方法可从一组值计算单个值。 LINQ 提供多个聚合方法,包括 xref:System.Linq.Enumerable.Average*、xref:System.Linq.Enumerable.Min* 和 xref:System.Linq.Enumerable.Max*。 可以通过向 xref:System.Collections.Generic.IEnumerable`1 接口添加扩展方法来创建自己的聚合方法。

下面的代码示例演示如何创建名为 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

使用从 xref:System.Collections.Generic.IEnumerable`1 接口调用其他聚合方法的方式为任何可枚举集合调用此扩展方法。

Note: 在 Visual Basic 中,您可以使用方法调用或标准的查询语法Aggregate或Group By子句。 有关详细信息,请参阅Aggregate 子句并组 By 子句。

下面的代码示例说明如何为类型 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

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

可以重载聚合方法,以便其接受各种类型的序列。 标准做法是为每种类型都创建一个重载。 另一种方法是创建一个采用泛型类型的重载,并使用委托将其转换为特定类型。 还可以将两种方法结合。

为每种类型创建重载

可以为要支持的每种类型创建特定重载。 下面的代码示例演示 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

现在便可以为 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
创建一般重载

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

下面的代码展示 Median 方法的重载,该重载将 xref:System.Func`2 委托作为参数。 此委托采用泛型类型 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

现在,可以为任何类型的对象序列调用 Median 方法。 如果类型不具有自己的方法重载,必须手动传递委托参数。 在 Visual Basic 中,可以实现此目的使用 lambda 表达式。 此外,如果您使用Aggregate或Group By子句而不是方法调用中的,可以传递任何值或处于范围内,此子句的表达式。

下面的代码示例演示如何为整数数组和字符串数组调用 Median 方法。 对于字符串,将计算数组中字符串长度的中值。 该示例演示如何将 xref:System.Func`2 委托参数传递给每个用例的 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

添加返回集合的方法

可以使用会返回值序列的自定义查询方法来扩展 xref:System.Collections.Generic.IEnumerable`1 接口。 在这种情况下,该方法必须返回类型 xref:System.Collections.Generic.IEnumerable`1 的集合。 此类方法可用于将筛选器或数据转换应用于值序列。

下面的示例演示如何创建名为 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

可使用从 xref:System.Collections.Generic.IEnumerable`1 接口调用其他方法的方式对任何可枚举集合调用此扩展方法,如下面的代码中所示:

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

请参阅

历史资料。此文对应 2019-08-18 的中文文档快照,适用产品版本和命令行为以原文为准。

来源与署名:Microsoft 和文档贡献者。固定版本原文。文档采用 CC BY 4.0,示例代码采用 MIT 授权。本站将 Markdown 转为 HTML,规范化链接,移除外部媒体和导航标记。

资料来源与适用范围

资料来源
Microsoft / .NET 中文文档历史快照
适用范围
历史中文快照 2019-08-18;详见原文产品版本;文档日期 07/20/2015
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-16
授权说明
CC BY 4.0(文档)/ MIT(示例代码)

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。