List去重的实现
程序员文章站
2022-05-23 22:11:49
List 当T为值类型的时候 去重比较简单,当T为引用类型时,一般根据业务需要,根据T的中几个属性来确定是否重复,从而去重。 查看System.Linq下的Enumerable存在一个去重方法 通过实现IEqualityComparer比较器来实现对象的比较。 IEqualityComp ......
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();