Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Método Enumerable.Distinct<TSource> (IEnumerable<TSource>, IEqualityComparer<TSource>)

 

Retorna os elementos distintos de uma sequência usando um IEqualityComparer<T> especificado para comparar valores.

Namespace:   System.Linq
Assembly:  System.Core (em System.Core.dll)

public static IEnumerable<TSource> Distinct<TSource>(
	this IEnumerable<TSource> source,
	IEqualityComparer<TSource> comparer
)

Parâmetros

source
Type: System.Collections.Generic.IEnumerable<TSource>

A sequência da qual os elementos duplicados serão removidos.

comparer
Type: System.Collections.Generic.IEqualityComparer<TSource>

Um IEqualityComparer<T> para comparar valores.

Valor Retornado

Type: System.Collections.Generic.IEnumerable<TSource>

Um IEnumerable<T> que contém elementos distintos da sequência de origem.

Parâmetros de Tipo

TSource

O tipo dos elementos de source.

Exception Condition
ArgumentNullException

source é null.

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in csprcs or For Each in vbprvb.

The M:System.Linq.Enumerable.Distinct``1(System.Collections.Generic.IEnumerable{``0},System.Collections.Generic.IEqualityComparer{``0}) method returns an unordered sequence that contains no duplicate values. If comparer is null, the default equality comparer, P:System.Collections.Generic.EqualityComparer`1.Default, is used to compare values.

The following example shows how to implement an equality comparer that can be used in the M:System.Linq.Enumerable.Distinct``1(System.Collections.Generic.IEnumerable{``0},System.Collections.Generic.IEqualityComparer{``0}) method.

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;
    }

}

After you implement this comparer, you can use a sequence of Product objects in the M:System.Linq.Enumerable.Distinct``1(System.Collections.Generic.IEnumerable{``0},System.Collections.Generic.IEqualityComparer{``0}) method, as shown in the following example.

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

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 3.5
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1
Retornar ao início
Mostrar: