在C#中,有多种方法可以实现去重操作。以下是一些常见的去重方法及其性能对比:
使用HashSetpublic static IEnumerable<T> Distinct<T>(this IEnumerable<T> source){ return source.Distinct(EqualityComparer<T>.Default);}HashSet
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source){ return source.Distinct();}这种方法与使用HashSet
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source){ return source.GroupBy(x => x).Select(g => g.First());}这种方法使用GroupBy()对数据进行分组,然后选择每个分组的第一个元素。它可以保留原始数据的顺序,但性能较差,尤其是在处理大量数据时。
使用Dictionary<TKey, TValue>:public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source){ return source.GroupBy(x => x).Select(g => g.Key);}这种方法类似于使用Dictionary<TKey, TValue>,但它只返回键。它可以保留原始数据的顺序,但性能较差,尤其是在处理大量数据时。
总结:
如果顺序不重要,推荐使用HashSet

