当前位置: 移动技术网 > IT编程>开发语言>.net > List去重的实现

List去重的实现

2018年11月02日  | 移动技术网IT编程  | 我要评论

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

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网