Enumerable..::.Distinct<(Of <(TSource>)>) 方法 (IEnumerable<(Of <(TSource>)>))

更新:2007 年 11 月

通过使用默认的相等比较器对值进行比较返回序列中的非重复元素。

命名空间:  System.Core(在 System.Core.dll 中)

Visual Basic(声明)
<ExtensionAttribute> _
Public Shared Function Distinct(Of TSource) ( _
    source As IEnumerable(Of TSource) _
) As IEnumerable(Of TSource)
Visual Basic (用法)
Of TSource)
Dim returnValue As IEnumerable(Of TSource)

returnValue = source.Distinct()
C#
static IEnumerable<TSource> Distinct<TSource>(
    this IEnumerable<TSource> source
)
Visual C++
[ExtensionAttribute]
public:
generic<typename TSource>
static IEnumerable<TSource>^ Distinct(
    IEnumerable<TSource>^ source
)
J#
J# 支持使用泛型 API,但是不支持新泛型 API 的声明。
JScript
JScript 不支持泛型类型或方法。

类型参数

TSource

source 中的元素的类型。

返回值

类型:

一个 )

,包含源序列中的非重复元素。

使用说明

在 Visual Basic 和 C# 中,可以在 扩展方法(C# 编程指南)
异常 条件
ArgumentNullException

sourcenullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing

此方法通过使用延迟执行实现。即时返回值为一个对象,该对象存储执行操作所需的所有信息。只有通过直接调用对象的 GetEnumerator 方法或使用 Visual C# 中的 foreach(或 Visual Basic 中的 For Each)来枚举该对象时,才执行此方法表示的查询。

Distinct<(Of <(TSource>)>)(IEnumerable<(Of <(TSource>)>)) 方法返回不包含重复值的无序序列。它使用默认的相等比较器 Default 对值进行比较。

在 Visual Basic 查询表达式语法中,Distinct 子句转换为 Distinct 的一个调用。

下面的代码示例演示如何使用 Distinct<(Of <(TSource>)>)(IEnumerable<(Of <(TSource>)>)) 返回序列中的非重复元素。

Visual Basic
' Create a list of integers.
Dim ages As New List(Of Integer)(New Integer() _
                                 {21, 46, 46, 55, 17, 21, 55, 55})

' Select the unique numbers in the List.
Dim distinctAges As IEnumerable(Of Integer) = ages.Distinct()

Dim output As New System.Text.StringBuilder("Distinct ages:" & vbCrLf)
For Each age As Integer In distinctAges
    output.AppendLine(age)
Next

' Display the output.
MsgBox(output.ToString)

' This code produces the following output:
'
' Distinct ages:
' 21
' 46
' 55
' 17

int> { 21, 46, 46, 55, 17, 21, 55, 55 };

IEnumerable<int> distinctAges = ages.Distinct();

Console.WriteLine("Distinct ages:");

foreach (int age in distinctAges)
{
    Console.WriteLine(age);
}

/*
 This code produces the following output:

 Distinct ages:
 21
 46
 55
 17
*/

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-18
  • 2021-12-30
  • 2022-02-10
  • 2021-06-13
猜你喜欢
  • 2021-11-25
  • 2021-08-09
  • 2022-12-23
  • 2021-06-13
  • 2022-12-23
  • 2021-11-23
  • 2022-12-23
相关资源
相似解决方案