在C#中,有多種方法可以實(shí)現(xiàn)去重操作。以下是一些常見的去重方法及其性能對比:
public 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()對數(shù)據(jù)進(jìn)行分組,然后選擇每個分組的第一個元素。它可以保留原始數(shù)據(jù)的順序,但性能較差,尤其是在處理大量數(shù)據(jù)時。
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source)
{
return source.GroupBy(x => x).Select(g => g.Key);
}
這種方法類似于使用Dictionary<TKey, TValue>,但它只返回鍵。它可以保留原始數(shù)據(jù)的順序,但性能較差,尤其是在處理大量數(shù)據(jù)時。
總結(jié):