Hooked on LINQ

Hooked on LINQ - Developers' Wiki
for .NET Language Integrated Query

Companion book for this site
LINQ to Objects Using C# 4.0:
Using and Extending LINQ to Objects and Parallel LINQ (PLINQ)
Quick Search

Advanced Search »
{TOC}
Namespace:System.Linq
Assembly:System.Core.dll
Extends:IEnumerable<T>

Back to Standard Query Operator Index


Edit

Introduction

The Distinct operator eliminates duplicate elements from a sequence.

Edit

Method Signatures

// 1 - Returns each element, once at most if it is a duplicate. 
public static IEnumerable<TSource> Distinct<TSource>(
    this IEnumerable<TSource> source)
 
// New in January CTP
// 2 - Returns each element, once at most if it is a duplicate. 
// A custom function to determine equality is used.
public static IEnumerable<TSource> Distinct<TSource>(
    this IEnumerable<TSource> source, 
    IEqualityComparer<TSource> comparer)



Edit

Exceptions

Throws an ArgumentNullException if source is null

Edit

Pseudo-code

Overload 1
If source is null, throw an ArgumentNullException.
Iterate the source sequence.
Check to see if this element value has already been returned (Uses EqualityComparer<TSource>.Default)
If this element value hasn't been returned, Add it to the list of those that has and Return the current element (pick up from here when the next element is requested).

Overload 2
If source is null, throw an ArgumentNullException.
Iterate the source sequence.
Check to see if this element value has already been returned (Uses the comparer function provided for equality evaluation)
If this element value hasn't been returned, Add it to the list of those that has and Return the current element (pick up from here when the next element is requested).

Edit

Loop Count

This operator implements the standard deferred execution iterator pattern. This means, no looping will occur until the result is iterated over..

Edit

Code Samples

public static void DistinctExample()
{
    string[] names = new string[] { "Peter", "Paul", "Mary", 
        "Peter", "Paul", "Mary", "Janet" };
 
    var q = (from s in names
            select s).Distinct();
 
    foreach (var name in q) {
        Console.WriteLine(name);
    }
 
    Console.ReadLine();
}

Century 21 Broker Properti Jual Beli Sewa Rumah Indonesia
Peter
Paul
Mary
Janet

If you would like to comment on this page, click on the Discuss button located on the top-right of each page. Feel free to edit any mistakes or omissions you find. If you have an objection or find in-appropriate content then contact the administrator. This website is not affiliated with Microsoft®, all content and opinions are those of the specific author and some advice, solutions and article may contain unintentional errors - please use care. Other websites by this author: Focused Objective, Geek Speak Decoded.