Hooked on LINQ

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

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

C# Simple example showing removal of duplicates from a sequence of strings.

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



Edit

C# Shows all public methods in this assembly, with duplicates removed.

 
 
// The second CSharp example showing usage of a custom IEQualityComparer<MethodInfo> object to generate a distinct
// sequence of MethodInfo objects based on the name of the method. 
 
    /// <summary>
    /// Enabless us to find a distinct list based on the MethodInfo.Name property.
    /// </summary>
    public class MethodInfoNameComparer : IEqualityComparer<MethodInfo>
    {
        public bool Equals(MethodInfo x, MethodInfo y)
        {
            if (x == null || y == null)
                return false;
            else
                return x.Name.ToLower() == y.Name.ToLower();
        }
 
        public int GetHashCode(MethodInfo obj)
        {
            return obj.Name.GetHashCode();
        }
    }
 
    MethodInfoNameComparer methodInfoComparer = new MethodInfoNameComparer();
 
    // Take 1:  using Query operator methods.
    var t1 = Assembly.GetExecutingAssembly().GetTypes()
                     .SelectMany(t => t.GetMembers())
                     .Where(t => t.MemberType == MemberTypes.Method && ((MethodInfo) t).IsPublic )
                     .Select( t => t as MethodInfo )
                     .Distinct(methodInfoComparer)
                     .OrderBy(m => m.Name);
 
    // Take 2:  using query expression syntax.  A little less straightforward.
    var t2 = (from type in Assembly.GetExecutingAssembly().GetTypes()
              from member in type.GetMembers()
              where member.MemberType == MemberTypes.Method && ((MethodInfo) member).IsPublic
              orderby member.Name
              select member as MethodInfo).Distinct(methodInfoComparer);
 



Edit

VB Shows all public methods in this assembly, with duplicates removed.

Public Sub Linq()
 
    Dim nList = From m In _
        (From t In _
            Assembly.GetExecutingAssembly.GetTypes(), _
            m In t.GetMembers() _
         Where m.MemberType = MemberTypes.Method AndAlso CType(m, MethodInfo).IsPublic _
         Select Item = CType(m, MethodInfo) _
         Order By Item.Name) _
         Select m.Name _
         Distinct
 
        For Each m In nList
            Console.WriteLine(m)
        Next
End Sub

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. Powered by ScrewTurn Wiki version 2.0.33. Some of the icons created by FamFamFam.