"C #" to use the Enumerable.distinct method to re-

Source: Internet
Author: User

Enumerable. The Distinct method is a common LINQ extension method that belongs to the System.Linq enumerable method, which can be used to remove duplicate elements from an array, a collection, and to customize the deduplication rules.

There are two overloaded methods:

        //        //Summary://returns a non-repeating element in a sequence by using the default equality comparer to compare values. //        //Parameters://Source://the sequence from which to remove the repeating element. //        //type parameter://TSource://The type of the element in source. //        //return Result://a system.collections.generic.ienumerable<t> that contains non-repeating elements in the source sequence. //        //Exception://System.ArgumentNullException://source is null.          Public StaticIenumerable<tsource> distinct<tsource> ( ThisIenumerable<tsource>source); //        //Summary://returns a non-repeating element in a sequence by using the specified system.collections.generic.iequalitycomparer<t> to compare values. //        //Parameters://Source://the sequence from which to remove the repeating element. //        //Comparer://the system.collections.generic.iequalitycomparer<t> used to compare values. //        //type parameter://TSource://The type of the element in source. //        //return Result://a system.collections.generic.ienumerable<t> that contains non-repeating elements in the source sequence. //        //Exception://System.ArgumentNullException://source is null.          Public StaticIenumerable<tsource> distinct<tsource> ( ThisIenumerable<tsource> source, iequalitycomparer<tsource> comparer);

The first method takes no arguments, and the second method needs to pass a System.collections.generic.iequalitycomparer<t> implementation object

1. Value type element collection de-weight

list<intnew list<int112234  55= Console.WriteLine (s));

Execution results are: 1 2 3 4 5

2. Reference type element collection go to weight

First, customize a student class

     Public classStudent { Public stringName {Get;Private Set; }  Public intId {Get;Private Set; }  Public stringHobby {Get;Private Set; }  PublicStudent (stringNameintIdstringHobby) {             This. Name =name;  This. Id =ID;  This. Hobby =Hobby; }        /// <summary>        ///easy output, overriding ToString method/// </summary>        /// <returns></returns>         Public Override stringToString () {return string. Format ("{0}\t{1}\t{2}", This. Name, This. Id This.        Hobby); }    }
View Code

Use the distinct method without parameters to remove the weight

list<student> list =NewList<student>() {                 NewStudent ("James",1,"Basketball"),                NewStudent ("James",1,"Basketball"),                NewStudent ("Kobe",2,"Basketball"),                NewStudent ("Curry",3,"Football"),                NewStudent ("Curry",3,"Yoga")            }; List. Distinct (). ToList (). ForEach (S= Console.WriteLine (S.tostring ()));

Execution Result:

Visible, and no duplicate records are removed.

The distinct method without the comparer parameter is compared by using the default comparer of the IEqualityComparer interface, for reference types, the default comparer compares its reference address , and each element in the assembly is a new instance. The reference addresses are different, so they are not deleted as duplicate records.

Therefore, we consider the use of the second overloaded method.

Create a new class that implements the IEqualityComparer interface. note the implementation of the GetHashCode method, only hashcode the same will be compared

     Public class Compare:iequalitycomparer<student>    {        publicbool  Equals (Student x, Student y)        {            return x.id = = y.id;   You can customize the deduplication rule, where the same ID is used as a duplicate record, regardless of the student's hobby.         }        publicint GetHashCode (Student obj)        {            return  obj. Id.gethashcode ();        }    }

and then call

List. Distinct (new Compare ()). ToList (). ForEach (s = Console.WriteLine (S.tostring ()));

Execution Result:

We follow the ID to give this set to go to success!

3. How to write a scalable weight-down method

     Public classCompare<t, c>: iequalitycomparer<t>    {        PrivateFunc<t, c>_getfield;  PublicCompare (Func<t, c>GetField) {             This. _getfield =GetField; }         Public BOOLEquals (t x, t y) {returnEqualitycomparer<c>.        Default.equals (_getfield (x), _getfield (y)); }         Public intGetHashCode (T obj) {returnEqualitycomparer<c>. Default.gethashcode ( This. _getfield (obj)); }    }     Public Static classCommonhelper {/// <summary>        ///custom DISTINCT extension methods/// </summary>        /// <typeparam name= "T" >to go to the heavy object class</typeparam>        /// <typeparam name= "C" >Custom de-weight field type</typeparam>        /// <param name= "source" >to go to the heavy object</param>        /// <param name= "GetField" >gets the delegate for the Custom de-weight field</param>        /// <returns></returns>         Public StaticIenumerable<t> Mydistinct<t, C> ( ThisIenumerable<t> source, Func<t, c>GetField) {            returnSource. Distinct (NewCompare<t, c>(GetField)); }    }
View Code

Call:

List. Mydistinct (s=>s.id). ToList (). ForEach (s = Console.WriteLine (S.tostring ()));

The use of generics, delegates, extension methods and other knowledge points. Various de-weight scenarios that can be used with any collection

"C #" to use the Enumerable.distinct method to re-

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.