List去重的實現


List<T> 當T為值類型的時候 去重比較簡單,當T為引用類型時,一般根據業務需要,根據T的中幾個屬性來確定是否重復,從而去重。

查看System.Linq下的Enumerable存在一個去重方法

    /// <summary>Returns distinct elements from a sequence by using a specified <see cref="T:System.Collections.Generic.IEqualityComparer`1" /> to compare values.</summary>
        /// <param name="source">The sequence to remove duplicate elements from.</param>
        /// <param name="comparer">An <see cref="T:System.Collections.Generic.IEqualityComparer`1" /> to compare values.</param>
        /// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
        /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains distinct elements from the source sequence.</returns>
        /// <exception cref="T:System.ArgumentNullException">
        ///         <paramref name="source" /> is <see langword="null" />.</exception>
        [__DynamicallyInvokable]
        public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
        {
            if (source == null)
            {
                throw Error.ArgumentNull("source");
            }
            return DistinctIterator(source, comparer);
        }

通過實現IEqualityComparer<T>比較器來實現對象的比較。

IEqualityComparer<T>的簡單實現,通過委托來比較對象

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Extensions
{
    public delegate bool ComparerDelegate<T>(T x, T y);

    /// <summary>
    /// list比較
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ListCompare<T> : IEqualityComparer<T>
    {
        private ComparerDelegate<T> _comparer;

        public ListCompare(ComparerDelegate<T> @delegate)
        {
            this._comparer = @delegate;
        }

        public bool Equals(T x, T y)
        {
            if (ReferenceEquals(x, y))
            {
                return true;
            }
            if (_comparer != null)
            {
                return this._comparer(x, y);
            }
            else
            {
                return false;
            }
        }

        public int GetHashCode(T obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
}

使用方法:

list= List.Distinct(new ListCompare<Path>
                ((x, y) => x.Latitude == y.Latitude && x.Longitude == y.Longitude)).ToList();

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM