您的位置:首页 > 其它

在foreach中使用distinct查找不重复记录

2010-01-17 09:27 661 查看
Enumerable..::.Distinct<(Of <(TSource>)>) 方法 (IEnumerable<(Of <(TSource>)>))

更新:2007 年 11 月

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

命名空间: System.Linq
程序集: 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 (用法)
Dim source As IEnumerable(Of TSource)
Dim returnValue As IEnumerable(Of TSource)

returnValue = source.Distinct()


C#
public 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 中的元素的类型。

参数

source
类型:System.Collections.Generic..::.IEnumerable<(Of <(TSource>)>)

要从中移除重复元素的序列。

返回值

类型:System.Collections.Generic..::.IEnumerable<(Of <(TSource>)>)

一个 IEnumerable<(Of <(T>)>),包含源序列中的非重复元素。

使用说明

在 Visual Basic 和 C# 中,可以在 IEnumerable<(Of <(TSource>)>) 类型的任何对象上将此方法作为实例方法来调用。当使用实例方法语法调用此方法时,请省略第一个参数。有关更多信息,请参见扩展方法 (Visual Basic)扩展方法(C# 编程指南)


异常

异常条件
ArgumentNullExceptionsource 为 nullNothingnullptrnull 引用(在 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

[align=center][/align]复制代码
' 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


C#

[align=center][/align]复制代码
List<int> ages = new List<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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: