List<T> 當T為值類型的時候 去重比較簡單,當T為引用類型時,一般根據業務需要,根據T的中幾個屬性來確定是否重覆,從而去重。 查看System.Linq下的Enumerable存在一個去重方法 通過實現IEqualityComparer<T>比較器來實現對象的比較。 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();