Enumerable.Distinct 方法

定義

從序列傳回獨特的項目。

多載

Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

使用指定的 IEqualityComparer<T> 來比較值,以便從序列傳回獨特的項目。

Distinct<TSource>(IEnumerable<TSource>)

使用預設的相等比較子來比較值,以便從序列傳回獨特的項目。

備註

結果序列未排序。

Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

來源:
Distinct.cs
來源:
Distinct.cs
來源:
Distinct.cs

使用指定的 IEqualityComparer<T> 來比較值,以便從序列傳回獨特的項目。

C#
public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Generic.IEqualityComparer<TSource> comparer);
C#
public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Generic.IEqualityComparer<TSource>? comparer);

類型參數

TSource

source 項目的類型。

參數

source
IEnumerable<TSource>

要移除重複項目的序列。

comparer
IEqualityComparer<TSource>

用來比較值的 IEqualityComparer<T>

傳回

IEnumerable<TSource>

IEnumerable<T>,其中包含來源序列中的獨特項目。

例外狀況

sourcenull

範例

下列範例示範如何實作可用於 方法的 Distinct 相等比較子。

C#
public class Product
{
    public string Name { get; set; }
    public int Code { get; set; }
}

// Custom comparer for the Product class
class ProductComparer : IEqualityComparer<Product>
{
    // Products are equal if their names and product numbers are equal.
    public bool Equals(Product x, Product y)
    {

        //Check whether the compared objects reference the same data.
        if (Object.ReferenceEquals(x, y)) return true;

        //Check whether any of the compared objects is null.
        if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
            return false;

        //Check whether the products' properties are equal.
        return x.Code == y.Code && x.Name == y.Name;
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.

    public int GetHashCode(Product product)
    {
        //Check whether the object is null
        if (Object.ReferenceEquals(product, null)) return 0;

        //Get hash code for the Name field if it is not null.
        int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();

        //Get hash code for the Code field.
        int hashProductCode = product.Code.GetHashCode();

        //Calculate the hash code for the product.
        return hashProductName ^ hashProductCode;
    }
}

實作這個比較子之後,您可以在 方法中使用Distinct物件序列Product,如下列範例所示:

C#
Product[] products = { new Product { Name = "apple", Code = 9 },
                       new Product { Name = "orange", Code = 4 },
                       new Product { Name = "apple", Code = 9 },
                       new Product { Name = "lemon", Code = 12 } };

// Exclude duplicates.

IEnumerable<Product> noduplicates =
    products.Distinct(new ProductComparer());

foreach (var product in noduplicates)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:
    apple 9
    orange 4
    lemon 12
*/

備註

這個方法是使用延後執行來實作。 立即傳回值是一個物件,會儲存執行動作所需的所有資訊。 除非直接呼叫其 GetEnumerator 方法或在 C# 或 foreachFor Each Visual Basic 中使用 來列舉對象,否則不會執行這個方法所代表的查詢。

方法 Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>) 會傳回不含重複值的未排序序列。 如果 為 comparernull,則會使用預設相等比較子 Default來比較值。

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Distinct<TSource>(IEnumerable<TSource>)

來源:
Distinct.cs
來源:
Distinct.cs
來源:
Distinct.cs

使用預設的相等比較子來比較值,以便從序列傳回獨特的項目。

C#
public static System.Collections.Generic.IEnumerable<TSource> Distinct<TSource> (this System.Collections.Generic.IEnumerable<TSource> source);

類型參數

TSource

source 項目的類型。

參數

source
IEnumerable<TSource>

要移除重複項目的序列。

傳回

IEnumerable<TSource>

IEnumerable<T>,其中包含來源序列中的獨特項目。

例外狀況

sourcenull

範例

下列程式代碼範例示範如何使用 Distinct<TSource>(IEnumerable<TSource>) 從整數序列傳回不同的專案。

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

如果您想要從某些自定義數據類型的物件序列傳回不同的專案,則必須在 類別中實 IEquatable<T> 作泛型介面。 下列程式代碼範例示範如何在自定義數據類型中實作此介面,並提供 GetHashCodeEquals 方法。

C#
public class MyProduct : IEquatable<MyProduct>
{
    public string Name { get; set; }
    public int Code { get; set; }

    public bool Equals(MyProduct other)
    {
        //Check whether the compared object is null.
        if (Object.ReferenceEquals(other, null)) return false;

        //Check whether the compared object references the same data.
        if (Object.ReferenceEquals(this, other)) return true;

        //Check whether the products' properties are equal.
        return Code.Equals(other.Code) && Name.Equals(other.Name);
    }

    // If Equals() returns true for a pair of objects
    // then GetHashCode() must return the same value for these objects.

    public override int GetHashCode()
    {

        //Get hash code for the Name field if it is not null.
        int hashProductName = Name == null ? 0 : Name.GetHashCode();

        //Get hash code for the Code field.
        int hashProductCode = Code.GetHashCode();

        //Calculate the hash code for the product.
        return hashProductName ^ hashProductCode;
    }
}

實作此介面之後,您可以在 方法中使用Distinct<TSource>(IEnumerable<TSource>)一連串Product的物件,如下列範例所示:

C#
MyProduct[] products = { new MyProduct { Name = "apple", Code = 9 },
                       new MyProduct { Name = "orange", Code = 4 },
                       new MyProduct { Name = "apple", Code = 9 },
                       new MyProduct { Name = "lemon", Code = 12 } };

// Exclude duplicates.

IEnumerable<MyProduct> noduplicates =
    products.Distinct();

foreach (var product in noduplicates)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:
    apple 9
    orange 4
    lemon 12
*/

備註

這個方法是使用延後執行來實作。 立即傳回值是一個物件,會儲存執行動作所需的所有資訊。 除非直接呼叫其 GetEnumerator 方法或在 C# 或 foreachFor Each Visual Basic 中使用 來列舉對象,否則不會執行這個方法所代表的查詢。

方法 Distinct<TSource>(IEnumerable<TSource>) 會傳回不含重複值的未排序序列。 它會使用預設相等比較子、 Default來比較值。

在 Visual Basic 查詢表達式語法中, Distinct 子句會轉譯為的 Distinct調用。

默認的相等比較子 Default是用來比較實 IEquatable<T> 作泛型介面之型別的值。 若要比較自定義數據類型,您必須實作此介面,並提供您自己的 GetHashCodeEquals 方法給類型。

如需使用 IEqualityComparer<T> 來定義自訂比較子的範例,請參閱 Distinct<TSource>(IEnumerable<TSource>, IEqualityComparer<TSource>)

另請參閱

適用於

.NET 9 和其他版本
產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0