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>)

 

Retorna os elementos distintos de uma sequência usando o comparador de igualdade padrão para comparar valores.

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

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

Parâmetros

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

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

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}) method returns an unordered sequence that contains no duplicate values. It uses the default equality comparer, P:System.Collections.Generic.EqualityComparer`1.Default, to compare values.

In vbprvb query expression syntax, a Distinct clause translates to an invocation of M:System.Linq.Enumerable.Distinct``1(System.Collections.Generic.IEnumerable{``0}).

The default equality comparer, P:System.Collections.Generic.EqualityComparer`1.Default, is used to compare values of the types that implement the T:System.IEquatable`1 generic interface. To compare a custom data type, you need to implement this interface and provide your own M:System.Object.GetHashCode and M:System.Object.Equals(System.Object) methods for the type.

For an example that uses T:System.Collections.Generic.IEqualityComparer`1to define a custom comparer, see M:System.Linq.Enumerable.Distinct``1(System.Collections.Generic.IEnumerable{``0},System.Collections.Generic.IEqualityComparer{``0}).

The following code example demonstrates how to use M:System.Linq.Enumerable.Distinct``1(System.Collections.Generic.IEnumerable{``0}) to return distinct elements from a sequence of integers.

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

If you want to return distinct elements from sequences of objects of some custom data type, you have to implement the T:System.IEquatable`1 generic interface in the class. The following code example shows how to implement this interface in a custom data type and provide M:System.Object.GetHashCode and M:System.Object.Equals(System.Object) methods.

public class Product : IEquatable<Product>
{
    public string Name { get; set; }
    public int Code { get; set; }

    public bool Equals(Product 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;
    }
}

After you implement this interface, you can use a sequence of Product objects in the M:System.Linq.Enumerable.Distinct``1(System.Collections.Generic.IEnumerable{``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();

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: