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

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

更新:2007 年 11 月

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

命名空间:  System.Linq
程序集:  System.Core(在 System.Core.dll 中)

C#
public static IEnumerable<TSource> Distinct<TSource>(
    this IEnumerable<TSource> source
)

类型参数

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# 编程指南)
异常 条件
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>)>)) 返回序列中的非重复元素。

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
*/

原文地址:https://www.cnblogs.com/atravellers/p/1649879.html