linq 剔除重复项
使用的时候,只需要
result = result.DistinctBy(p=>p.IP);
public static partial class DistinctExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
//HashSet<TKey> seenKeys = new HashSet<TKey>();
//foreach (TSource element in source)
//{
// if (seenKeys.Add(keySelector(element)))
// {
// yield return element;
// }
//}
return source.Distinct(new CommonEqualityComparer<TSource, TKey>(keySelector));
}
public class CommonEqualityComparer<T, V> : IEqualityComparer<T>
{
private readonly Func<T, V> keySelector;
public CommonEqualityComparer(Func<T, V> keySelector)
{
this.keySelector = keySelector;
}
public bool Equals(T x, T y)
{
return EqualityComparer<V>.Default.Equals(keySelector(x), keySelector(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer<V>.Default.GetHashCode(keySelector(obj));
}
}
}